学无先后,达者为师

网站首页 编程语言 正文

python在文件中倒序查找个关键词

作者:程序小小小猿 更新时间: 2022-08-30 编程语言

python在文件中倒序查找个关键单词,忽略大小写来匹配,并将关键单词所在行作为结果返回,以单词输入顺序作为优先度实现返回(目前只返回第1个单词所在行,可实现多个返回)

#coding = utf-8

# @author : dj
import re


# the second param 你想要寻找的字母(顺序影响结果,顺序即优先度)
# 调用方式: (fname,copyright,source)

def extractOriginalAgency(fname,*dependingList):
count_ = len(dependingList)
result = ["none"] * count_
n =0
with open(fname, 'r', encoding='utf-8') as f:


try:
lines = f.readlines() #读取所有行
i = 0
while(True):
# find from the ending of the passage

string = lines[i]

for j in range(0,count_):
if(result[j] == "none" ):
if (match(string,dependingList[j])):
# 匹配成功
result[j] =string
n = n+1

# 当找到所有单词是即不必再往下找
if(n == count_):
break

i += 1;
except:
pass

# 找到目标所在行后
finResult = "none"
temp = "none"
# 优先返回有
for z in range(0,count_):
if(temp =="none" and result[z] !="none" ):
temp = result[z]
if(finResult =="none"):
finResult = temp

return finResult


def match(string,reString):
# 用restring 匹配string
matchObj = re.match(reString,string,re.IGNORECASE)

if(matchObj):
return True
else:
return False


 


原文链接:https://blog.csdn.net/m0_67911416/article/details/126593363

栏目分类
最近更新