我正在嘗試編寫一個函數,該函數接受一個鍵(以及其他內容)並返回文件中此鍵後的單詞。下面的代碼可以工作,但前提是密鑰恰好是文件中的第一個短語。任何人都可以指出我要出錯的地方嗎?重新匹配的Python變量
def findmatch(key, split_by, tempsl, filename, temp):
rx=r''+key+'(.*)'
f = open(tempsl + filename, 'r', encoding='windows-1252')
for eachline in f:
string=re.match(rx, eachline)
if string:
return (string.group().split(' ')[split_by])
else:
return "didn't work"
嘗試re.findall。 –
......或're.find'如果你只需要第一個匹配 – spectras
我試過,但以後使用string.group() – user5826447