gpt4 book ai didi

Python-多次替换一个单词

转载 作者:行者123 更新时间:2023-11-30 23:29:01 25 4
gpt4 key购买 nike

问题:我有一种情况,每次句子中的单词发生变化时,我都需要用 dc 替换句子中的单词。句子是:

甜蜜坏不不长是自行车否是

在接下来的几次中,句子将不断更改为:

甜蜜坏否否长是自行车是否

甜蜜坏否否短是汽车是否

因此,输出应如下所示:

甜蜜坏否否dc是dc dc dc

我想用 dc 替换从第一个句子到下一个句子的第一个更改实例。我写了一段代码,但看起来不对。我哪里出错了?

 dont_care = "dc"
hyp_curr = []
hyp_next = []

def create_hypothesis(stVal):
splitVal = stVal.split()
global hyp_curr
global hyp_next

if not hyp_curr:
hyp_curr = (' '.join(w for w in splitVal if w not in hyp_curr))
return hyp_curr
else:
hyp_next = splitVal
print hyp_curr
print hyp_next

for wordc in hyp_curr.split():
for wordn in hyp_next:
if hash(wordc) != hash(wordn):
hyp_curr = hyp_curr.replace(wordn,dont_care)
return hyp_curr

最佳答案

>>> s = "Sweet Bad No No Long Yes Bike No Yes"
>>> s1 = "Sweet Bad No No Long Yes Bike Yes No"
>>> map(lambda x: x[0]==x[1] and x[0] or 'dc', zip(s.split(), s1.split()))
['Sweet', 'Bad', 'No', 'No', 'Long', 'Yes', 'Bike', 'dc', 'dc']
>>> ' '.join(_)
'Sweet Bad No No Long Yes Bike dc dc'

或者:

>>> [x[0]==x[1] and x[0] or 'dc' for x in zip(s.split(), s1.split())]
['Sweet', 'Bad', 'No', 'No', 'Long', 'Yes', 'Bike', 'dc', 'dc']

关于Python-多次替换一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357851/

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