您可以传递一个callable来
re.sub告诉它如何处理match对象。
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-groupsre.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 maintainre.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>'
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)