【发布时间】: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