【问题标题】:what is the error in following python code以下python代码中的错误是什么
【发布时间】:2012-09-24 01:08:07
【问题描述】:

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

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

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

【问题讨论】:

  • 定义u时缺少引号"
  • 仍然无法正常工作。 'the' 'a' 之类的停用词不会被删除。

标签: python nltk stop-words


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您正在做的问题是 list.remove(x) 仅删除 第一次 出现x,而不是每个 x。要删除每个实例,您可以使用filter,但我会选择这样的:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 虽然这可能是 OP 的正确方法和可接受的答案,但应该注意的是,非停用词的顺序和计数不会被保留。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多