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/