python - 如何将文本文件中的一行与其中存在的字符串匹配?

标签 python arrays regex string

我需要将字符串数组的每个索引与文本文件进行匹配,如果找到匹配项,我需要完整的匹配行。但是我的代码没有执行任何操作。

这是我的代码:

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/

相关文章:

python - 如何将多处理与请求模块一起使用?

python - Matplotlib - 两个不同范围的不同颜色图

ruby - 在 Ruby 矩阵中交换列或行

c - 如何在 C 中将 char 数组 case [0] 和 [1] 连接到 char 指针?

javascript - 如何替换不包括特定单词的字符串?

python - 选择 Pandas 中特定行上方和下方的 N 行

python - MySQL 更新报告错误,我缺少什么?

sql - 如何将 array_agg() 用于 varchar[]

javascript - HTML5 输入模式不区分大小写

javascript - 如何在javascript中删除文件路径,只保留文件名,而不考虑文件系统