我正在寻找最快的方法来替换非常大的字符串中的大量子字符串。这是我用过的两个例子。
findall() 感觉更简单、更优雅,但它花费的时间惊人。
finditer() 在一个大文件中快速搜索,但我不确定这是正确的方法。
这是一些示例代码。请注意,我感兴趣的实际文本是大小约为 10MB 的单个字符串,这两种方法存在巨大差异。
import re
def findall_replace(text, reg, rep):
for match in reg.findall(text):
output = text.replace(match, rep)
return output
def finditer_replace(text, reg, rep):
cursor_pos = 0
output = ''
for match in reg.finditer(text):
output += "".join([text[cursor_pos:match.start(1)], rep])
cursor_pos = match.end(1)
output += "".join([text[cursor_pos:]])
return output
reg = re.compile(r'(dog)')
rep = 'cat'
text = 'dog cat dog cat dog cat'
finditer_replace(text, reg, rep)
findall_replace(text, reg, rep)
更新 为测试添加了 re.sub 方法:
def sub_replace(reg, rep, text):
output = re.sub(reg, rep, text)
return output
结果
re.sub() - 0:00:00.031000
finditer() - 0:00:00.109000
findall() - 0:01:17.260000
最佳答案
标准方法是使用内置的
re.sub(reg, rep, text)
顺便说一下,您的版本之间性能差异的原因是您的第一个版本中的每个替换都会导致整个字符串被重新复制。复制速度很快,但是当您一次复制 10 MB 时,足够的副本会变慢。
关于python - 用于搜索和替换大字符串的最快 Python 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4893506/