Python单词替换功能异常:仅最后一组替换生效的原因排查
问题排查与修复
核心问题
你的代码仅最后一组替换生效的原因是:每次替换操作都基于原始的sentence变量,而非上一次替换后的结果。循环里每次都用未修改过的原始句子生成新结果,前面的替换会被后续循环覆盖,最终只保留最后一次替换的效果。
错误代码分析
看这段循环逻辑:
for key, value in replacement_words.items(): new_sentence = sentence.replace(str(key), str(value))
每次循环都将原始sentence替换后的结果赋值给new_sentence,相当于每次都从头开始替换,之前的修改完全没被保留。在你的示例中,循环顺序是automobile→car、manufacturer→maker、children→kids,前两次替换的结果都被第三次覆盖,最终只留下children替换成kids的效果。
修复方案
只需要让每次替换都基于上一次的替换结果即可,修改后的代码如下:
words = input() word_pairs = words.split(' ') replacement_words = {} # 存入替换字典 for pair in word_pairs: split_pair = pair.split(' ') replacement_words[split_pair[0]] = split_pair[1] # 读取目标句子并执行替换 sentence = input() new_sentence = sentence # 初始化新句子为原始内容 for key, value in replacement_words.items(): new_sentence = new_sentence.replace(str(key), str(value)) print(new_sentence)
测试效果
输入替换对:automobile car manufacturer maker children kids
输入目标句子:The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.
修复后输出:
The car maker recommends car seats for kids if the car doesn't already have one.
内容的提问来源于stack exchange,提问作者denofhay
相关产品推荐
相关产品推荐

