python - Python - 用匹配的对值替换正则表达式匹配
问题描述
假设我有一个与运行时可用的 5 位代码相关的别名列表:
aliasPairs = [(12345,'bob'),(23456,'jon'),(34567,'jack'),(45678,'jill'),(89012,'steph')]
我想找到一种简洁的表达方式:将行中的id替换为匹配的别名,例如:
line = "hey there 12345!"
line = re.sub('\d{5}', value in the aliasPairs which matches the ID, line)
print line
应该输出:
hey there bob!
Python 专业人士如何以简洁的方式编写枚举表达式?
谢谢和欢呼!
解决方案
当您对两类数据(例如五位代码和别名)进行一对一映射时,请考虑使用字典。然后很容易访问任何特定的别名,给定它的代码:
import re
aliases = {
"12345":"bob",
"23456":"jon",
"34567":"jack",
"45678":"jill",
"89012":"steph"
}
line = "hey there 12345!"
line = re.sub('\d{5}', lambda v: aliases[v.group()], line)
print(line)
结果:
hey there bob!
推荐阅读
- python - 在python 3中,如何创建一个元组,它是一个对象,元组中有多少个元素?应作为函数参数有效
- c++ - “NewUserClient”应该如何实现
- javascript - 如何绘制单击多边形 vue-konva
- python - 从箱线图生成随机值
- c# - 在其他项目中看不到命名空间
- javascript - JQuery悬停效果未在第一次悬停时开始
- python - TextMate 不在 python 中执行 encode() 函数
- html - 如何重定向到个人资料页面并在 Django 中查看登录用户的数据?
- web-scraping - 如何从重定向链接中抓取网址?
- swift - 循环自日期以来的天/周/月/年(swift)