【问题标题】:Replacing all instances of substring using a dictionary使用字典替换子字符串的所有实例
【发布时间】:2018-12-19 23:30:25
【问题描述】:

我知道有一种方法可以替换所有匹配某种模式的实例,如下所示:re.sub(r'x', 'y', string)

但是有没有办法用字典中最后一个字符的值对应的值替换所有实例,如#a#b

dict = {'a': '1', 'b': 2', ... }

所以abc#bcd#ae 变成abc2cd1e 等等。

【问题讨论】:

    标签: python regex pattern-matching


    【解决方案1】:

    re.sub 的第二个参数(替换任何匹配项)可以是可调用的。如果是这样,则为每个匹配项使用单个参数(匹配对象)调用它,并将其结果替换为字符串。所以你可以这样做:

    d = {'a': 'A', 'b': 'B'}
    s = '#a #b and #c'
    def replace_it(m):
        return d.get(m.group('key'), m.group(0))
    print re.sub('#(?P<key>[a-zA-Z]+)', replace_it, s)
    

    【讨论】:

    • 不错!这正是我一直在寻找的。谢谢。
    【解决方案2】:

    您可以替换字符串中找到的所有匹配项:

    mydict = {'a':'1', 'b':'2'}
    mystr = '#a#b'
    for k, v in mydict.items():
        mystr = mystr.replace('#' + k, v)
    

    【讨论】:

      【解决方案3】:

      如果您知道要替换的确切内容,则不需要正则表达式。这些更适合您寻找模式,而不是完全匹配。 string.replace 应该可以解决这个问题。

      string = "a#acbb#bd"
      dictionary = {'a':'1', 'b':'2'}
      newstring1 = string.replace('#a', dictionary['a'])
      newstring = newstring1.replace('#b', dictionary['b'])
      print(newstring)
      >>>a1cbb2d
      

      【讨论】:

      • 是的,但是您必须遍历字典中每个键的字符串。我在想可能有一种方法可以一次性将它们全部搞定,而无需循环。
      猜你喜欢
      • 2011-09-29
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 2021-08-16
      • 2017-09-04
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多