我有一个字典和字符串,如:
d = {'ASAP':'as soon as possible', 'AFAIK': 'as far as I know'}
s = 'I will do this ASAP, AFAIK. Regards, X'
我想用字符串中的dict键替换dict的值并返回
I will do this <as soon as possible>, <as far as I know>. Regards, X.
我用
pattern = re.compile(r'\b(' + '|'.join(d.keys())+r')\b')
result=pattern.sub(lambda x: '<'+d[x.group()]+'>',s)
print"result:%s" % result
我有一本字典:
{'will you wash some pants for me please :-)': 'text'}
笑脸导致错误。如何更改正则表达式以适应任何字符,如表情符号?
答案 0 :(得分:7)
您需要使用re.escape()
转义任何正则表达式元字符:
pattern = re.compile(r'\b(' + '|'.join(map(re.escape, d)) + r')\b')