【发布时间】:2014-02-04 05:09:06
【问题描述】:
我有一个字典和字符串,例如:
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'}
笑脸导致错误。如何更改我的正则表达式以适应笑脸等任何字符?
【问题讨论】:
-
你试过在按键上使用
re.escape吗? -
你真正要问的是如何在正则表达式中转义特殊字符......字典与它无关。