我正在尝试写一个拼写检查器,告诉您句子中哪些单词的拼写错误。 它应该从输入中读取特定的句子,并查看该句子中的单词是否属于给定列表。如果它们不是一部分,则应打印出不合适的单词。如果一切正确,则应打印“确定”。但是,我无法让它仅打印不正确的单词,而不能遍历整个列表并多次打印OK。
到目前为止,这是我的代码:
dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize',
'sign', 'the', 'to', 'uncertain']
sentence = input()
sentence = sentence.split()
for word in sentence:
if word not in dictionary:
print(word)
elif word in dictionary:
print("OK")
break
答案 0 :(得分:1)
这是因为当您看到错误的单词时使用break
。这意味着它将停止循环,并因此找不到其他不正确的单词。
您想要的代码如下:
dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize',
'sign', 'the', 'to', 'uncertain']
sentence = input()
sentence = sentence.split()
found_incorrect_word = False
for word in sentence:
if word not in dictionary:
print(word)
found_incorrect_word = True # no break here
if not found_incorrect_word:
print("OK")
答案 1 :(得分:1)
您的问题是,您在输入正确单词的那一刻就开始努力。试试这个:
dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize',
'sign', 'the', 'to', 'uncertain']
sentence = input()
sentence = sentence.split()
incorrect = False
for word in sentence:
if word not in dictionary:
print(word)
incorrect = True
if not incorrect:
print("OK")
答案 2 :(得分:1)
使用列表理解来检测错误的单词
dictionary = ['all', 'an', 'and', 'as', 'closely', 'correct', 'equivocal',
'examine', 'indication', 'is', 'means', 'minutely', 'or', 'scrutinize',
'sign', 'the', 'to', 'uncertain']
sentence = input('Enter sentence: ')
sentence = sentence.split()
incorrect_words = [word for word in sentence if not word in dictionary]
if incorrect_words:
print(*incorrect_words, sep='\n')
else:
print('All words OK')
或更简洁
incorrect_words = [word for word in input('Enter sentence: ').split() if not word in dictionary]
if incorrect_words:
print(*incorrect_words, sep='\n')
else:
print('All words OK')