我需要将字符串数组的每个索引与文本文件进行匹配,如果找到匹配项,我需要完整的匹配行。但是我的代码没有执行任何操作。
这是我的代码:
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)
最佳答案
从某种意义上说,这将相当有效地完成它,因为它只遍历文件一次,不会一次将其全部读入内存,并检查每一行是否有所有可能的单词。
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))
关于python - 如何将文本文件中的一行与其中存在的字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857766/