如何在 python 中使用正则表达式替换字符串的多个单词?

How to replace multiple words of a string using regex in python?

我有这样的字典:

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

谢谢

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

除此之外,您还可以使用回顾和回顾正则表达式。对于后视,您希望它不是单词 (?<!\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