我需要将我的字符串数组的每个索引与文本文件匹配,如果找到匹配项,我需要完整的匹配行。但是我的代码没有做任何事情。
这是我的代码:
for element in array:
elementstring=''.join(element)
with open(file_location,mode="r", encoding='utf8') as file:
reader=file.readlines()
for line in reader:
words=re.split(' ',line)
if elementstring in line:
print(line)
答案 0 :(得分:1)
这样做会相当有效,因为它只会传递一个文件,不会立即将其全部读入内存,并检查每一行是否有所有可能的单词。
file_location = 'somefile.txt'
words = 'word1', 'word2', 'word3'
with open(file_location, mode="r", encoding='utf8') as file:
for line in (line.rstrip() for line in file):
if any((word in line) for word in words):
print('matches: {!r}'.format(line))