You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

zyBooks实验6.19 单词替换Python代码输出异常问题排查

zyBooks Lab 6.19 替换词实验输出异常排查

问题现象

完成zyBooks Lab Activity 6.19 - Replacement Words实验时,程序输出与预期不符,初步判断问题与print语句位置、sentence.replace逻辑相关。程序运行后会输出多轮替换的中间结果,无法输出单次最终替换结果。

问题复现信息

原实现代码

word_pairs = {}

tokens = input().split()
sentence = input()

step = 2
for index in range(0,len(tokens), step):
    key = tokens[index]
    value = tokens[index+1]
    
    word_pairs[key] = value
    for original, new in word_pairs.items():
        sentence = sentence.replace(original, new)
        
        print(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. 

实际运行输出

The car manufacturer recommends car seats for children if the car doesn't already have one.
The car manufacturer recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for kids if the car doesn't already have one.

根因分析

代码存在两处明确错误:

  • 替换流程嵌套错误:外层循环每向word_pairs存入一组替换词对,就立刻遍历当前字典内的所有规则执行全句替换,每新增一条规则就重复跑一次全量替换,产生了大量多余的中间步骤。
  • 输出语句位置错误:print(sentence)被放在内层替换循环的缩进块内,每完成一次单个单词的替换就会打印当前句子状态,因此所有中间替换结果都会被输出。

修正方案

调整代码执行顺序,拆分「构建替换字典」和「执行替换」两个步骤,将输出语句移到所有替换操作完成后:

  • 第一阶段仅遍历输入的tokens,完整构建所有替换词对的字典,此阶段不执行任何替换操作
  • 等所有替换规则全部存入字典后,再遍历字典对句子执行统一替换
  • 所有替换全部完成后,仅打印一次最终的句子结果

修正后可运行代码

word_pairs = {}

tokens = input().split()
sentence = input()

step = 2
# 构建替换词字典
for index in range(0, len(tokens), step):
    original_word = tokens[index]
    replace_word = tokens[index+1]
    word_pairs[original_word] = replace_word

# 统一执行所有替换
for original, new in word_pairs.items():
    sentence = sentence.replace(original, new)

# 输出最终结果
print(sentence)

内容的提问来源于stack exchange,提问作者Ca1amity_Jane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 22:36:36