社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python检查单词

DelphiProgrammer • 4 年前 • 595 次点击  

我被一个简单的问题困住了。我有一本英语单词词典,还有一个要检查的文本样本。我必须对照字典核对样本中的每个单词,我使用的代码是错误的。

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

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43411
 
595 次点击  
文章 [ 6 ]  |  最新文章 4 年前
Georg Schölly
Reply   •   1 楼
Georg Schölly    14 年前

你的 refDict 可能是错的。这个 in 关键字检查值是否在字典的关键字中。我相信你把你的话当作价值观。

我建议使用 set 而不是字典。

knownwords = set("dog", "cat")
knownwords.add("apple")

text = "The dog eats an apple."
for word in text.split(" "):
    # to ignore case word is converted to lowercase
    if word.lower() not in knownwords:
        print word
# The
# eats
# an
# apple.       <- doesn't work because of the dot
Gareth Simpson
Reply   •   2 楼
Gareth Simpson    14 年前

refdict中的单词是键还是值?

您的代码将只看到密钥:例如:

refDict = { 'w':'x', 'y':'z' }
for word in [ 'w','x','y','z' ]:
  if word not in refDict:
  print word

印刷品:

x
z

你想要什么;

如果单词不在refdict.values()中

当然,这相当于假设您的字典是一个实际的python字典,这似乎是一种存储单词列表的奇怪方式。

Tendayi Mawushe
Reply   •   3 楼
Tendayi Mawushe    14 年前

如果你把钥匙放进去 refDict 是拼写正确的单词。如果拼写正确的单词是dict中的值,则需要如下内容:

for word in checkList:
    if word not in refDict.values():
        print word

字典作为映射而不是列表或集合存储有什么原因吗?python dict包含名称-值对例如,我可以使用以下映射: {"dog":23, "cat":45, "pony":67} 为了存储一个单词和页码的索引,可以在某本书中找到。在你的例子中,你的口述是什么到什么的映射?

Grumdrig
Reply   •   4 楼
Grumdrig    14 年前

显然,“单词不在refdict中”总是被认为是真的。这可能是因为refdict或checklist的内容与您想象的不同。它们是元组还是字符串列表?

SilentGhost
Reply   •   5 楼
SilentGhost    14 年前

考虑去掉单词中可能存在的空白,并将两个集合中的所有单词更改为相同的大小写。这样地:

word.strip().lower()

这样你就可以确定你在比较苹果和苹果。

mjv
Reply   •   6 楼
mjv    14 年前

您拥有的代码片段是功能性的。例如,请参见

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

因此,词典的内容必须与你所想的不同,否则清单上的单词就不会 确切地 当它们出现时(例如,使用空格或大写;请参阅print语句中repr()(*)的使用,以帮助识别前者的情况)。

调试建议:关注清单中的第一个单词(或者您怀疑的第一个单词将在字典中找到)。然后,对于这个单词和这个单词,请详细打印它,包括它的长度、两边的括号等,对于清单外的单词和字典中相应的键…

(*)是John Machin提出的建议。相反,我经常在打印时使用方括号或其他字符('['+word+']'),但是repr()在输出中更为精确。