检查列表中的单词是否拼写正确

Check if words are spelled correctly in list

我得到了一本字典,其中包含以下单词:

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

我正在尝试编写一个拼写检查器,它可以判断输入句子中的哪些单词拼写错误。

预期输出是:

A) 在新的一行打印拼写错误的单词

B) 只有所有单词都拼写正确,打印OK

这是我到目前为止想出的代码:

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

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

for x in text:
    if x not in dictionary:
        counter += 1
        print(x, end='\n')
    elif not counter:
        print("OK")

给出了两个示例输入和输出作为预期结果的示例:

示例输入 1:

srutinize is to examene closely and minutely

示例输出 1:

srutinize

examene

示例输入 2:

all correct

示例输出 2:

OK

代码适用于输入 1,但输入 2 而不是打印 OK 打印的是 all correct 而不是 OK

您的更新代码就快完成了。你应该在循环结束后检查一次计数器,而不是对每个单词都检查一次:

for x in text:
    if x not in dictionary:
        counter += 1
        print(x, end='\n')

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

还有一种使用列表理解来解决问题的更奇特的方法:

text = input().split()

typos = [word for word in text if word not in dictionary]
if typos:
    print("\n".join(typos))
else:
    print("OK")