【问题标题】:Check if words are spelled correctly in list [closed]检查列表中的单词是否拼写正确[关闭]
【发布时间】:2021-07-30 08:26:21
【问题描述】:

我得到了一本包含以下单词的字典:

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

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

预期的输出是:

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

B) 只有在所有单词拼写正确时,才可以打印

这是我目前想出的代码:

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

【问题讨论】:

  • 刚刚更新了帖子。真的需要一些指导,拜托。

标签: python loops split list-comprehension any


【解决方案1】:

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

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

【讨论】:

  • 谢谢塞尔丘克,这对我们很有帮助。
猜你喜欢
  • 2011-05-28
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多