【问题标题】:Python matching lines of a file with a list of stringsPython将文件的行与字符串列表匹配
【发布时间】:2016-10-14 21:25:43
【问题描述】:

高级要求是我需要一个等效的“grep -f match_str_file search_file”。

我有一个字符串列表,我需要在给定的文本文件中找到这些字符串。 该字符串可以出现在文件的任何行中的任何位置。

什么是实现这一目标的有效方法?

matchstr = ['string1', 
'string2', 
'string3',
...
'string1000']

with open('some_text_file') as file:
    for line in file:
        if <any matchstr> in line:
            print( 'Found a match!', matchstr[x])

【问题讨论】:

  • 我不明白。为什么这个问题被否决了?做一个简单的问题并不会弄错。如有其他原因,应注明。
  • 您的“效率”指标是什么。你尝试过什么“低效”的方法?为什么它不起作用。
  • 当有人投出一票接近的票时,您应该阅读该消息。它通常会很好地解释随之而来的反对票。

标签: python python-3.x string-matching


【解决方案1】:

试试这个:

matchstr = ['string1', 
'string2', 
'string3',
...
'string1000']

matches = []
def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
while 1:
    lines = file.readlines(file_len("fjiop.txt"))
    if not lines:
        break
    for line in lines:
        matches.append([match, line] for match in matchstr if match in line)

请注意,这将在生成器中创建生成器,以便循环使用:

for i in matches:
    for j in i:
        #do stuff

【讨论】:

  • 感谢您的回答。但这对我没有帮助。我特别问“什么是实现这一目标的有效方法?”我需要每天数百次将 1M 行长文件与 1K 组字符串进行比较。除非它是有效的,否则它不会成功。
  • 也许这样会更快;它在我的电脑上要快得多。
猜你喜欢
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 2017-07-29
  • 1970-01-01
  • 2014-01-09
  • 2021-11-30
相关资源
最近更新 更多