【问题标题】:Multiple substitutions of a string in a text, without matching substrings [duplicate]文本中字符串的多次替换,没有匹配的子字符串[重复]
【发布时间】:2019-11-02 11:29:22
【问题描述】:

我尝试使用不匹配子字符串的正则表达式替换文本中的不同字符串。

我用:

v = {"Anna" : 'UNNK'} 
text2 = "My name is Anna not Maria-Anna"
for i in v.keys():
    w = r"\b{}(?![-|\w*])".format(i)
    reg = re.compile(w)
text3 = reg.sub('UNK', text2) 
print(text3) 

代码返回:

“我的名字是 UNK 而不是 Maria-UNK”

我想返回的地方: “我叫 UNK,不是 Maria-Anna”

【问题讨论】:

    标签: python regex


    【解决方案1】:

    你太复杂了。这可以使用字符串replace 来完成,并在键和值周围添加空格,确保您只替换整个单词(而不是单词内部):

    v = {"Anna" : 'UNNK'} 
    text2 = "My name is Anna not Maria-Anna"
    
    text2 = f' {text2} '
    for k, v in v.items():
        text2 = text2.replace(f' {k} ', f' {v} ')
    
    text2 = text2[1:-1] 
    print(text2) 
    # My name is UNNK not Maria-Anna
    

    【讨论】:

      【解决方案2】:

      使用否定的lookaround 确保我们前后没有非空格:

      v = {"Anna" : 'UNNK'} 
      text2 = "My name is Anna not Maria-Anna"
      for i in v.keys():
          w = r"(?<!\S){}(?!\S)".format(i)
          reg = re.compile(w)
      text3 = reg.sub('UNK', text2) 
      print(text3) 
      

      输出:

      My name is UNK not Maria-Anna
      
      • (?&lt;!\S)否定后视,使之前没有非空格
      • (?!\S)负前瞻,使后面没有非空格

      【讨论】:

        【解决方案3】:

        也许你需要

        w = r"(?<= ){}(?= )".format(i)
        

        顺便说一句,您对字典的定义尚不清楚,因为您从不使用键的值...

        【讨论】:

          【解决方案4】:

          在您提供的示例中,您可以使用环视:

          (?<=\s|^)Anna(?=\s|$)
          

          解释:

          (?&lt;=\s|^) - 正向后视:确保前面是空格 \s 或字符串开头 ^

          (?=\s|$) - 正向前瞻:确保后面是空格 \s 或字符串结尾 $

          Demo

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-11-05
            • 2022-01-07
            • 1970-01-01
            • 2011-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多