用Python来检查单词

0 python

我遇到了一个简单的问题.我有一本英语单词词典,还有一个要检查的示例文本.我必须检查示例中的每个单词与字典,我正在使用的代码是错误的.

for word in checkList:      # iterates through every word in the sample
    if word not in refDict: # checks if word is not in the dictionary
         print word         # just to see if it's recognizing misspelled words
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,当它通过循环时它打印出每个单词,而不仅仅是拼写错误的单词.有人可以解释这个并提供解决方案吗?非常感谢!

mjv*_*mjv 6

您拥有的代码片段功能齐全.例如,参见

>>> refDict = {'alpha':1, 'bravo':2, 'charlie':3, 'delta':4}
>>> s = 'he said bravo to charlie O\'Brian and jack Alpha'
>>> for word in s.split():
...   if word not in refDict:
...       print(repr(word))  # by temporarily using repr() we can see exactly
...                          #  what the words are like
...
'he'
'said'
'to'
"O'Brian"
'and'
'jack'
'Alpha'     # note how Alpha was not found in refDict (u/l case difference)
Run Code Online (Sandbox Code Playgroud)

因此,字典内容必须与您的想法不同,或者核对表之外的单词与它们出现的不完全相同(例如,使用空格或大小写;请参阅print语句中使用repr()(*)来帮助识别前者).

调试建议:关注清单中的第一个单词(或者您怀疑在字典中找到的第一个单词).然后,对于这个单词和这个单词,打印它的详细信息,其长度,两侧的括号等,对于核对清单中的单词和字典中的相应键...

(*)repr()是John Machin的建议.相反,我经常使用括号或其他字符作为print('['+ word +']'),但repr()在其输出中更严格.


dsi*_*ard 5

考虑剥离可能存在的任何空格的单词,并将两个集合中的所有单词更改为相同的大小写.像这样:

word.strip().lower()
Run Code Online (Sandbox Code Playgroud)

这样你可以确保你比较苹果和苹果.