栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python Regex子-使用Match作为替换中的Dict键

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python Regex子-使用Match作为替换中的Dict键

您可以传递一个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>'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651173.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号