以下python代码中的错误是什么

时间:2012-10-03 06:18:26

标签: python nltk stop-words

我想删除停用词。这是我的代码

import nltk
from nltk.corpus import stopwords
import string

u="The apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family (Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans."

v="An orange is a fruit of the orangle tree. it is the most cultivated tree fruits"

u=u.lower()
v=v.lower()

u_list=nltk.word_tokenize(u)
v_list=nltk.word_tokenize(v)

for word in u_list:
    if word in stopwords.words('english'):
        u_list.remove(word)
for word in v_list:
    if word in stopwords.words('english'):
        v_list.remove(word)

print u_list
print "\n\n\n\n"
print v_list

但只删除了一些停用词。请帮帮我这个

3 个答案:

答案 0 :(得分:1)

您正在执行的操作的问题是list.remove(x)仅删除x第一次次,而不是每个x。要删除每个实例,您可以使用filter,但我会选择以下内容:

u_list = [word for word in u_list if word not in stopwords.words('english')] 

答案 1 :(得分:0)

我会通过将拆分字词列表和停用词列表转换为set来删除这些字词并计算difference

u_list = list(set(u_list).difference(set(stopwords.words('english'))))

这应该正确地删除停用词的出现。

答案 2 :(得分:0)

我使用remove(x)函数在类似的代码段中挣扎了一段时间。我注意到只有大约50%的停用词被删除了。我知道这不是来自案件(我降低了我的话),也不是来自词语(strip())附加的puntuation或其他字符。我的理论(我是初学者)是当你删除一个令牌缩小列表时,索引和列表项会滑动,但循环从同一个索引继续。因此它不会循环每个单词。解决方案是使用非停止词和您想要保留的词来增加新列表。

相关问题