如何纠正这个问题发生在replace()?Python



我有这样一个句子:

s="This is my cat who is my ally and this is my dog who has started to finally act like one."

我想用其他单词替换句子中的某些单词。例子:

猫与蝙蝠,盟友与保护者。

现在问题出现在相似的单词上。例如ally和finally

s="This is my cat who is my ally and this is my dog who has started to finally act like one."
for r in (("cat", "bat"),("ally", "protector")):
    s = s.replace(*r)
print(s)

这应该给我:

这是我的蝙蝠,它是我的保护者,这是我的狗,它终于开始表现得像一个人了。

但是由于ally,它最终给了我以下影响的输出:

这是我的蝙蝠,它是我的保护者,这是我的狗,它开始像一个保护者一样行动。

它最终影响并转换为finprotector。我不想这样。如何解决这个问题?如有任何帮助,不胜感激。

对字典re.sub使用正则表达式, lambda如下:

import re
s = "This is my cat who is my ally and this is my dog who has started to finally act like one."
dct = {
    'cat': 'bat',
    'ally': 'protector'
}
regex = re.compile(r'b(' + '|'.join(map(re.escape, dct.keys())) + r')b')
print(regex.sub(lambda match: dct[match.group(0)], s))
# This is my bat who is my protector and this is my dog who has started to finally act like one.

注意,b表示换行符,允许匹配ally, ally ,但不匹配finally

您可以在replace中包含空格以仅选择单个单词。

s="This is my cat who is my ally and this is my dog who has started to finally act like one."
for r in ((" cat ", " bat "),(" ally ", " protector ")):
    s = s.replace(*r)
print(s)
This is my bat who is my protector and this is my dog who has started to finally act like one.

也许你想尝试正则表达式和re模块(特别是re.sub()方法)?

import re
line = re.sub(r'ballyb', 'protector', s)

最新更新