文本中多次替换字符串,无需匹配子字符串

2024-09-30 00:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用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"

我想返回的地方: “我的名字不是玛丽亚·安娜”


Tags: 字符串name文本forismynotreg
3条回答

使用负lookaround确保前后没有非空格:

v = {"Anna" : 'UNNK'} 
text2 = "My name is Anna not Maria-Anna"
for i in v.keys():
    w = r"(?<!\S){}(?!\S)".format(i)
    reg = re.compile(w)
text3 = reg.sub('UNK', text2) 
print(text3) 

输出:

My name is UNK not Maria-Anna
  • (?<!\S)负向后看,使前面没有非空格
  • (?!\S)负向前看,使后面没有非空格

你太复杂了。这可以通过使用字符串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

也许你需要

w = r"(?<= ){}(?= )".format(i)

顺便说一句,您对dict的定义还不清楚,因为您从不使用键的值。。。你知道吗

相关问题 更多 >

    热门问题