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
本文介绍了一个Python函数,用于在文件中从后向前查找指定的关键字,并返回包含这些关键字的行。该函数支持忽略大小写的匹配,并能按关键字的顺序优先返回结果。

1万+

被折叠的 条评论
为什么被折叠?



