簡體   English   中英

我在使用列表時遇到問題

[英]I'm having trouble with lists

我正在嘗試編寫一個拼寫檢查器,告訴您句子中哪些單詞拼寫錯誤。 它應該從輸入中讀取一個特定的句子,並查看該句子中的單詞是否是給定列表的一部分。 如果它們不是一部分,它應該打印出不合適的詞。 如果一切正確,它應該打印“OK”。 但是我遇到了麻煩,讓它只打印不正確的單詞,而不是遍歷整個列表並多次打印 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

這是因為當你看到一個不正確的詞時,你使用了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")

你的問題是你一說出正確的詞就突然爆發了。 試試這個:

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")

使用列表理解來檢測不正確的單詞

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM