【发布时间】: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)表示不是单词字符。