【问题标题】:How to replace multiple words of a string using regex in python?如何在python中使用正则表达式替换字符串的多个单词?
【发布时间】:2020-09-16 04:20:59
【问题描述】:

我有一本像这样的字典:

dic = { "xl": "xlarg", "l": "larg",'m':'medium'}

我想使用 re.sub 或类似方法查找 dic.keys 中的任何字符串(包括单个字母)并将其替换为键的值。

def multiple_replace(dict, text):
     # Create a regular expression  from the dictionary keys
     regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
    
     # For each match, look-up corresponding value in dictionary
     return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)

它适用于字符串中的单个字母,例如它将尺寸 m 更改为中尺寸,但它也会更改单词中的字母,例如将星期一更改为 mediumonday

谢谢

【问题讨论】:

  • 你能提供一些样本以及预期的输出吗?
  • 您可以在单个单词字符后跟 not 单词字符的情况下使用前瞻:"(%s)(?=\W)" 其中(?=....) 是前瞻,\W(大写 W)表示不是单词字符。

标签: python regex python-re


【解决方案1】:

您可以使用re.compilesub 方法查找匹配的子字符串并替换它们。这里的想法是通过使用 OR 语句 | 将所有键连接到一个模式中。然后,对于每个匹配项,您使用匹配的子字符串对替换字典进行查找。

除此之外,您还可以使用lookbehind 和lookahead 正则表达式。对于向后看,您希望它不是一个词 (?<!\w)。对于前瞻,您希望它也不是单词(?!\w)

总而言之,我们有:r"(?<!\w)(xl|l|m)(?!\w)"

这是一个例子:

def replace_substrings(s, d):
    p = "|".join(d.keys())
    p = r"(?<!\w)(" + p + r")(?!\w)"
    return re.compile(p).sub(lambda m: d[m.group(0)], s)
...


dic = {"xl": "xlarg", "l": "larg",'m':'medium'}
inputs = [
    "size m",
    "monday",
    "xl sell",
    "m size m l xl",
]

for input in inputs:
    print(replace_substrings(input, dic))

这将输出:

size medium
monday
xlarg sell
medium size medium larg xlarg

【讨论】:

  • 这是 OP 想要的。
  • @JohanL 我修好了,请再看看
猜你喜欢
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-24
  • 2022-11-07
相关资源
最近更新 更多