带有 nltk.wordnet.synsets 的 Python IF 语句

标签 python nltk wordnet

import nltk
from nltk import *
from nltk.corpus import wordnet as wn

output=[]
wordlist=[]

entries = nltk.corpus.cmudict.entries()

for entry in entries[:200]: #create a list of words, without the pronounciation since.pos_tag only works with a list
    wordlist.append(entry[0])

for word in nltk.pos_tag(wordlist): #create a list of nouns
    if(word[1]=='NN'):
        output.append(word[0])

for word in output:
    x = wn.synsets(word) #remove all words which does not have synsets (this is the problem)
    if len(x)<1:
        output.remove(word)

for word in output[:200]:
    print (word," ",len(wn.synsets(word)))

我试图删除所有没有同义词集的单词,但由于某种原因它不起作用。运行程序后,我发现即使一个单词的 len(wn.synsets(word)) = 0,它也不会从我的列表中删除。有人可以告诉我出了什么问题吗?

最佳答案

您无法迭代列表并同时删除当前项目。这是一个演示该问题的玩具示例:

In [73]: output = range(10)

In [74]: for item in output:
   ....:     output.remove(item)

您可能希望删除 output 中的所有项目。但其中一半仍然存在:

In [75]: output
Out[75]: [1, 3, 5, 7, 9]

为什么不能同时循环和删除:

想象一下,Python 在执行 for 循环 时使用内部计数器来记住当前项的索引。

当计数器等于 0(第一次循环)时,Python 执行

output.remove(item)

好吧。现在输出中少了一项。但随后 Python 将计数器增加到 1。因此 word 的下一个值是 output[1], 这是原始列​​表中的第三项。

0  <-- first item removed
1  <-- the new output[0] ** THIS ONE GETS SKIPPED **
2  <-- the new output[1] -- gets removed on the next iteration 

(解决方法)解决方案:

相反,要么迭代输出的副本,要么构建一个新列表。在这种情况下,我认为构建一个新列表会更有效:

new_output = []
for word in output:
    x = wn.synsets(word) 
    if len(x)>=1:
        new_output.append(word)

关于带有 nltk.wordnet.synsets 的 Python IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366924/

相关文章:

python - 是否可以模拟 Python 3.6 中的内置 len() 函数?

python - 过滤标点符号附近的停用词

python - 如何构建IMS开源语料库工作台和NLTK可读语料库?

python - nltk.TweetTokenizer 中的 Tokenize() 通过拆分返回整数

python - 从 Python 中的大文件中删除重复行

python - 如何迭代枚举的所有值,包括任何嵌套的枚举?

Python/Django : How to remove extra white spaces & tabs from a string?

python - wordnet路径相似度是可交换的吗?

nlp - 寻找不同词之间的语义相似性和关系

Java:使用 Wordnet 和 JWNL 保留词干后的点