gpt4 book ai didi

python - 如何在不使用python替换方法的情况下替换句子中的单词

转载 作者:行者123 更新时间:2023-11-30 22:27:53 25 4
gpt4 key购买 nike

我已经编写了一个函数来替换句子中的单词,而不使用Python内置的替换方法,问题是我的代码在边缘情况下失败,如果该单词与另一个单词组合,我应该将每个出现的 Maybe 替换为也许。看看我的代码

def replace_all (target,find,replace):
split_target = target.split()
result = ''
for i in split_target:
if i == find:
i = replace
result += i + ' '
return result.strip()
target = "Maybe she's born with it. Maybe it's Maybeline."
find = "Maybe"
replace = "Perhaps"
print replace_all(target, find, replace)

输出是:

Perhaps she's born with it. Perhaps it's Maybeline.

但我期待它打印这个:

Perhaps she's born with it. Perhaps it's perhapsline. 

请注意最后一个单词 Maybeline 应该更改为 Maybeline。我已经为此奋斗了一个星期了,任何帮助将不胜感激。

最佳答案

原因是您在空格上进行了分割,因此当您比较 i 时至find ,您正在比较 Maybeline.Maybe 。这不会匹配,因此您不会替换该匹配项。

如果您按要查找的值拆分,然后将各个部分与替换字符串连接起来,您将获得许多字符串,在 Maybe 处进行拆分曾经是,您可以使用 replace 加入这些它们之间的字符串:

def replace_all (target,find,replace):
return replace.join(target.split(find))

target = "Maybe she's born with it. Maybe it's Maybeline."
find = "Maybe"
replace = "Perhaps"

print(replace_all(target, find, replace))

> Perhaps she's born with it. Perhaps it's Perhapsline.

关于python - 如何在不使用python替换方法的情况下替换句子中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com