【问题标题】:python regex for string replacement用于字符串替换的python正则表达式
【发布时间】:2011-11-03 04:36:40
【问题描述】:

我想替换包含以下单词“$%word$%”的部分字符串 我想用对应键等于单词的字典的值替换它。

换句话说,如果我有一个字符串:“blahblahblah $%word$% blablablabla $%car$%” 和字典 {word:'wassup', car:'toyota'}

字符串将是“blahblahblah wassup blablablabla toyota”

如何在python中实现它,我正在考虑使用字符串替换和正则表达式。

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    re.sub与函数一起用作repl参数:

    import re
    
    text =  "blahblahblah $%word$% blablablabla $%car$%"
    words = dict(word="wassup", car="toyota")
    
    def replacement(match):
        try:
            return words[match.group(1)]  # Lookup replacement string
        except KeyError:
            return match.group(0)  # Return pattern unchanged
    
    pattern = re.compile(r'\$%(\w+)\$%')
    result = pattern.sub(replacement, text)
    

    如果你想在使用re.sub的时候通过替换表,使用functools.partial

    import functools
    
    def replacement(table, match):
        try:
            return table[match.group(1)]
        except:
            return match.group(0)
    
    table = dict(...)
    result = pattern.sub(functools.partial(replacement, table), text)
    

    ...或实现__call__的类:

    class Replacement(object):
        def __init__(self, table):
            self.table = table
        def __call__(self, match):
            try:
                return self.table[match.group(1)]
            except:
                return match.group(0)
    
     result = pattern.sub(Replacement(table), text)
    

    【讨论】:

    • 如果字典是用另一种方法创建的呢?我将如何实施替换?我无法为替换添加参数。
    • 与这个问题非常相似; stackoverflow.com/questions/7182546/…
    • @mabounassif - 让replacement 将字典作为参数,然后使用functools.partial() 创建一个传递字典的单参数包装函数。我会更新我的答案来举个例子。
    【解决方案2】:

    re 模块是您想要的。

    不过,您可能需要重新考虑对分隔符的选择。 $% 可能会出现问题,因为 $ 是正则表达式中的保留字符。不过,由您决定,只需记住在您的模式中使用 '\\$'r'\$'(这是一个原始字符串。如果您在 python 中执行正则表达式,这非常有用。)。

    【讨论】:

      【解决方案3】:
      import re
      
      text =  "blahblahblah $%word$% blablablabla $%car$%"
      words = dict(word="wassup", car="toyota")
      
      regx = re.compile('(\$%%(%s)\$%%)' % '|'.join(words.iterkeys()))
      
      print regx.sub(lambda mat: words[mat.group(2)], text)
      

      结果

      blahblahblah wassup blablablabla toyota
      

      【讨论】:

        猜你喜欢
        • 2022-11-07
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 2018-07-13
        • 2015-11-30
        • 2021-11-29
        相关资源
        最近更新 更多