【问题标题】:python how to increment vars in regex replacementspython如何在正则表达式替换中增加变量
【发布时间】:2018-01-15 19:29:25
【问题描述】:

我想用正则表达式替换文件中的多个模式。 到目前为止,这是我的(工作)代码:

import re

with open('test.txt', "r") as fp:
  text = fp.read()

result = re.sub(r'pattern', 'replacement', str)
result2 = re.sub(r'anotherpattern', 'anotherreplacement2', result)
...

with open('results.txt', 'w') as fp:
   fp.write(result_x)

这行得通。但是在每个新行中手动增加变量名称似乎是不优雅的。我怎样才能更好地增加它们?我认为它必须是一个for循环。但是怎么做呢?

【问题讨论】:

    标签: python regex increment


    【解决方案1】:

    使用过之前的结果就不需要了。您可以将新结果存储在同一个变量中:

    text = re.sub(r'pattern1', 'replacement1', text) # str() is a string constructor!
    text = re.sub(r'pattern2', 'replacement2', text)
    

    您还可以有一个模式和替换列表并循环遍历它:

    to_replace = [('pattern1', 'replacement1'), ('pattern2', 'replacement2')]
    for pattern,replacement in to_replace:
        text = re.sub(pattern, replacement, text)
    

    或者以更 Pythonic 的方式:

    to_replace = [('pattern1', 'replacement1'), ('pattern2', 'replacement2')]
    for pr in to_replace:
        text = re.sub(*pr, string=text)
    

    【讨论】:

    • 解决方案 1 是我正在寻找的。那很好,很好处理。其他解决方案看起来更 pyhtonic,但目前我对 Nr 感到满意。 1.
    【解决方案2】:

    我不太了解 Python,但我认为如果你想组合模式,
    您可以使用回调一次性完成。

    例子:

    def repl(m):
        contents = m.group(1)
        if m.group(1) != '':
            return sr1
        if m.group(2) != '':
            return sr2
        if m.group(3) != '':
            return sr3
        return m.group(0)
    
    
    print re.sub('(stuff1)|(stuff2)|(stuff3)', repl, text)
    

    而且,它也可以在回调中循环。
    例如,一个 var 包含固定的 number 个模式
    循环以测试匹配对象。
    必须有一个与
    相同大小(和位置)的替换数组 正则表达式中的组数。

    这会给您带来多少性能提升?
    一次性完成此操作,您将获得 指数 性能。

    请注意,一遍又一遍地重新检查相同的文本几乎是一个错误。想象一下,每次从一开始就一次一个字地搜索国会图书馆。这需要多长时间?

    【讨论】:

      猜你喜欢
      • 2011-03-12
      • 1970-01-01
      • 2022-07-08
      • 2021-12-17
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 2020-01-05
      相关资源
      最近更新 更多