Python的IF语句与nltk.wordnet.synsets

问题描述:

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

我想删除所有单词没有synsets,但由于某种原因,它不工作。在运行程序时,我发现即使一个单词有len(wn.synsets(word))= 0,它也不会从我的列表中删除。有人可以告诉我哪里出了问题?Python的IF语句与nltk.wordnet.synsets

您无法遍历列表并同时删除当前项目。这里是演示了该问题的玩具例子:

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

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

output.remove(item) 

精细。 output现在只有一个项目。但是Python随后将计数器递增为1.所以下一个字的值是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 

的(解决方法)的解决方案:

相反,无论是遍历一个副本output,或者建立一个新的列表。在这种情况下,我认为建立一个新清单更有效率:

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