【问题标题】:Python efficient way to search for a pattern in text filePython在文本文件中搜索模式的有效方法
【发布时间】:2021-10-06 08:40:38
【问题描述】:

我需要在一个不大的文本文件中找到一个模式。 因此,将整个文件加载到 RAM 对我来说不是问题 - 正如 here 建议的那样:

我尝试了两种方式:

with open(inputFile, 'r') as file:
    for line in file.readlines():
        for date in dateList:
            if re.search('{} \d* 1'.format(date), line):

with open(inputFile, 'r') as file:
    contents = file.read()
    for date in dateList:
        if re.search('{} \d* 1'.format(date), contents):

事实证明,第二个要快得多。

除了我在第二种方法中使用了更少的循环这一事实之外,还有其他解释吗?

【问题讨论】:

  • 很明显,在第二种情况下,您对整个文件文本执行一次匹配(re.search 只查找第一个匹配项)。在第一种情况下,您运行它的次数与文件中的行数一样多。第一段代码 sn -p 势必会花更多的时间。
  • 正确。我错过了多个电话 - 谢谢

标签: python-3.x performance python-re


【解决方案1】:

正如 cmets 中所指出的,这两个代码并不等效,因为第二个代码仅在整个文件中查找第一个匹配项。除此之外,第一个也更昂贵,因为(相对昂贵的)format 在所有日期上为每一行调用。存储正则表达式并预编译它们应该会有很大帮助。更好的是:您可以生成一个正则表达式来一次匹配所有日期,使用类似:

regexp = '({}) \d* 1'.format('|'.join('{}'.format(date) for date in dateList))

with open(inputFile, 'r') as file:
    contents = file.read()
    # Search the first matching date existing in dateList
    if re.search(regexp, contents):

请注意,如果您想要所有这些,可以使用findall

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多