您可以将一个可调用对象传递给re.sub,告诉它如何处理匹配对象。
s = re.sub(r'<(\w+)>', lambda m: replacement_dict.get(m.group()), s)
dict.get 的使用允许您在替换字典中没有所述单词时提供“后备”,即
lambda m: replacement_dict.get(m.group(), m.group())
# fallback to just leaving the word there if we don't have a replacement
我会注意到,当使用re.sub(和家庭,即re.split)时,当指定存在周围您想要替换的东西时,使用环视表达式通常更干净,这样你的比赛周围的东西不会被替换掉。所以在这种情况下,我会像这样写你的正则表达式
r'(?<=<)(\w+)(?=>)'
否则,您必须在lambda 中的括号内进行一些拼接。为了清楚我在说什么,举个例子:
s = "<sometag>this is stuff<othertag>this is other stuff<closetag>"
d = {'othertag': 'blah'}
#this doesn't work because `group` returns the whole match, including non-groups
re.sub(r'<(\w+)>', lambda m: d.get(m.group(), m.group()), s)
Out[23]: '<sometag>this is stuff<othertag>this is other stuff<closetag>'
#this output isn't exactly ideal...
re.sub(r'<(\w+)>', lambda m: d.get(m.group(1), m.group(1)), s)
Out[24]: 'sometagthis is stuffblahthis is other stuffclosetag'
#this works, but is ugly and hard to maintain
re.sub(r'<(\w+)>', lambda m: '<{}>'.format(d.get(m.group(1), m.group(1))), s)
Out[26]: '<sometag>this is stuff<blah>this is other stuff<closetag>'
#lookbehind/lookahead makes this nicer.
re.sub(r'(?<=<)(\w+)(?=>)', lambda m: d.get(m.group(), m.group()), s)
Out[27]: '<sometag>this is stuff<blah>this is other stuff<closetag>'