python - 文本中字符串的多次替换,不匹配子字符串
问题描述
我尝试使用正则表达式替换文本中的不同字符串而不匹配子字符串。
我用:
v = {"Anna" : 'UNNK'}
text2 = "My name is Anna not Maria-Anna"
for i in v.keys():
w = r"\b{}(?![-|\w*])".format(i)
reg = re.compile(w)
text3 = reg.sub('UNK', text2)
print(text3)
代码返回:
“我的名字是 UNK 不是 Maria-UNK”
我想返回的地方:“我的名字是 UNK 而不是 Maria-Anna”
解决方案
你太复杂了。这可以只使用replace
在键和值周围添加空格的字符串来完成,以确保您只替换整个单词(而不是单词内部):
v = {"Anna" : 'UNNK'}
text2 = "My name is Anna not Maria-Anna"
text2 = f' {text2} '
for k, v in v.items():
text2 = text2.replace(f' {k} ', f' {v} ')
text2 = text2[1:-1]
print(text2)
# My name is UNNK not Maria-Anna
推荐阅读
- javascript - 将必填字段设置为隐藏/显示切换
- python - 为什么我的“最大公分母”程序没有输出正确的信息?
- python - 在熊猫数据框中将单元格拆分为多行
- angular - 一种创建具有 n 个对象的静态列表的有效方法
- android - 调用 setHasOptionsMenu() 后无法更新 CollapsingToolbar 标题
- javascript - 具有重置功能的 D3js 缩放
- istio - 可以使用 Istio 0.8.0 对 TCP 服务进行熔断吗?
- python - 从csv读取包含单元格中字典的熊猫数据框
- firebase - 当我在 Firebase Cloud Functions 中使用 .on() 时会发生什么?
- python - 如何在特定情况下组合数据框?