Python:更快的正则表达式替换

mba*_*rov 3 python regex replace

我有一大堆大文件和一组需要在每个文件中替换的"短语".
"业务逻辑"强加了几个限制:

  • 匹配必须不区分大小写
  • 正则表达式中的空格,制表符和新行不能被忽略

我的解决方案(见下文)有点慢.如何在IO和字符串替换方面进行优化?

data = open("INPUT__FILE").read()
o = open("OUTPUT_FILE","w")
for phrase in phrases: # these are the set of words I am talking about
        b1, b2 = str(phrase).strip().split(" ")
        regex = re.compile(r"%s\ *\t*\n*%s"%(b1,b2), re.IGNORECASE)
        data = regex.sub(b1+"_"+b2,data)
o.write(data)
Run Code Online (Sandbox Code Playgroud)

更新:通过将所有文本转换为小写并删除来加速4倍re.IGNORECASE

and*_*oke 5

你可以避免为每个文件重新编译你的正则表达式:

precompiled = []
for phrase in phrases:
    b1, b2 = str(phrase).strip().split(" ")
    precompiled.append(b1+"_"+b2, re.compile(r"%s\ *\t*\n*%s"%(b1,b2), re.IGNORECASE))

for (input, output) in ...:
    with open(output,"w") as o:
        with open(input) as i:
            data = i.read()
            for (pattern, regex) in precompiled:
                data = regex.sub(pattern, data)
            o.write(data)
Run Code Online (Sandbox Code Playgroud)

它对于一个文件是相同的,但是如果你重复多个文件,那么你就是在重新使用正则表达式.

免责声明:未经测试,可能包含错别字.

[ 更新 ]也可以通过替换各种空格字符来简化正则表达式\s*.我怀疑你有一个错误,因为你想匹配" \t ",目前没有.