You need to enable JavaScript to run this app. Python 拼写检查器:仅在所有单词正确时输出 OK
优惠活动
大模型
产品
解决方案
定价
更多

Python 拼写检查器:仅在所有单词正确时输出 OK

问题原因

OK 的输出判断被放在了遍历单词的 for 循环内:只要当前单词拼写正确、且此前没遇到过错词,就会打印 OK。此时后续单词还未检查,若后面存在错词,就会出现提前输出 OK 的错误逻辑。

修复方案

将 OK 的判断移到整个循环执行完毕之后:先完成所有单词的检查、统计错词,再根据结果决定输出内容。

基于原代码的最小改动

dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
              'examine', 'indication', 'is', 'means', 'minutely', 'or',
              'scrutinize', 'sign', 'the', 'to', 'uncertain']

text = input().split()
error_count = 0

for word in text:
    if word not in dictionary:
        error_count += 1
        print(word)

if error_count == 0:
    print("OK")

改动点:

  • 删除循环内的 elif not counter 分支,避免提前输出
  • 所有单词遍历完成后,再根据错词计数判断:错词数为0时才打印一次 OK
  • print() 默认以换行结尾,原有 end='\n' 可以省略

更简洁的实现

可以直接用列表收集所有错词,省去手动维护计数器的步骤:

dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
              'examine', 'indication', 'is', 'means', 'minutely', 'or',
              'scrutinize', 'sign', 'the', 'to', 'uncertain']

word_list = input().split()
wrong = [w for w in word_list if w not in dictionary]

print('\n'.join(wrong) if wrong else "OK")

两种写法都能满足要求:

  • 存在错词时,每个错词单独占一行
  • 全部拼写正确时,仅输出一次 OK

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 07:06:05