У меня проблемы со списками - PullRequest
0 голосов
/ 02 августа 2020

Я пытаюсь написать программу проверки орфографии, которая сообщит вам, какие слова в предложении написаны неправильно. Предполагается, что он читает конкретное предложение c из ввода и проверяет, являются ли слова в этом предложении частью данного списка. Если они не являются частью, он должен напечатать слова, которые неуместны. Если все правильно, должно быть напечатано «ОК». Однако у меня возникли проблемы с тем, чтобы заставить его печатать ТОЛЬКО неправильные слова, а не l oop через весь список и печатать 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

Ответы [ 3 ]

1 голос
/ 02 августа 2020

Ваша проблема в том, что вы вырываете в ту минуту правильное слово. Попробуйте это:

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")
1 голос
/ 02 августа 2020

Использование списка для обнаружения неправильных слов

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')
1 голос
/ 02 августа 2020

Это потому, что вы используете break, когда видите неправильное слово. Это означает, что он останавливает l oop там, где он есть, и, следовательно, не находит другие неправильные слова.

Требуемый код выглядит следующим образом:

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")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...