【问题标题】:Are multilines regexp compatible with iterators?多行正则表达式与迭代器兼容吗?
【发布时间】:2019-09-27 18:24:48
【问题描述】:

迭代器和生成器现在是内存高效代码的标准。现在,每当我需要处理长列表时,我都会尽可能多地应用它们。有没有办法在通过迭代器迭代大文件 (>500Mb) 时使用多行正则表达式?

经典之道:

import re
my_regex = re.compile(r'some text', re.MULTILINE)

with open('my_large_file.txt', 'r') as f:
    text = f.read() # Stores the whole text in a list
                    # This is memory consuming    
result = my_regex.findall(text) 

迭代器方式:

import re
my_regex = re.compile(r'some text', re.MULTILINE)

with open('my_large_file.txt', 'r') as f:
    for line in f: # Use the file as an iterator and
                   # loop over the lines
                   # What could I do?

最小的工作示例:

大文件:

Lorem ipsum dolor sit amet, 
consectetur adipiscing elit, 
sed do eiusmod tempor. 
--------------------------------
Some text I want to capture
--------------------------------
Lorem ipsum dolor sit amet,
consectetur adipiscing elit, 
sed do eiusmod tempor.

我的正则表达式:

my_regex = re.compile(r"[-]+$\n(.+)\n\s[-]+", re.MULTILINE)   

【问题讨论】:

  • 您不需要正则表达式来匹配 that 类型的模式,您只需检查该行是否全是连字符,设置标志,保存下一行,如果下一个也是所有连字符,附加到结果列表中。如果您的模式是任意的,您可能会被迭代器方式卡住。
  • 您认为 multline 选项有什么不同?
  • 是不是因为你想遍历文件的行而不是读入整个文件,但是多行正则表达式需要多行?

标签: python regex python-3.x string iterator


【解决方案1】:

您可以做的是遍历文件行,并将它们连接到一个正在运行的文本,您可以使用正则表达式对其进行测试。找到匹配项后,您可以清空正在运行的文本。

text = ''
results = []
with open('my_large_file.txt', 'r') as f:
    for line in f:
        text += line
        result = my_regex.findall(text)
        if result:
            results += result
            text = ''

【讨论】:

    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2016-02-02
    • 2020-07-05
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多