我尝试使用regex替换文本中不同的字符串,而不使用匹配的子字符串。你知道吗
我使用:
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)
代码返回:
"My name is UNK not Maria-UNK"
我想返回的地方: “我的名字不是玛丽亚·安娜”
使用负lookaround确保前后没有非空格:
输出:
(?<!\S)
负向后看,使前面没有非空格(?!\S)
负向前看,使后面没有非空格你太复杂了。这可以通过使用字符串
replace
来实现,在关键字和值周围添加空格,确保只替换整个单词(而不是单词内部):也许你需要
顺便说一句,您对dict的定义还不清楚,因为您从不使用键的值。。。你知道吗
相关问题 更多 >
编程相关推荐