用Python去除停用词

0 投票
2 回答
2443 浏览
提问于 2025-04-18 01:47

我不明白为什么这段代码不管用。当我点击运行时,它显示“去掉停用词后:None”。有人能帮我解决这个问题吗?非常感谢。

 stop_words = ["the", "of", "a", "to", "be", "from", "or"]
 last = lower_words.split()

 for i in stop_words:
     lastone = last.remove(i)
     print "\nAAfter stopwords removal:\n",lastone

2 个回答

0

这里有一个函数,它接收一段文字,然后返回去掉一些常见无用词后的文字。这个函数的工作原理是忽略掉一个字典里列出的无用词。我使用了.lower()这个函数来处理每一个单词,因为大多数无用词的列表都是小写字母,而我们的文字可能不是小写的。

def cut_stop_words(text,stopwords):
  new_text= ''
  for i in text.split():

    if (i.lower()) in stopwords:
         pass
     else:
         new_text= new_text.strip() + ' ' + i

  return new_text
2

list.remove()这个函数会直接修改列表,并且返回None

所以当你执行last.remove(i)时,它会从列表last中删除第一个出现的i,然后返回None,因此lastone总是会被设置为None

根据你想要做的事情,你可能希望从stop_words中删除所有出现的某个项目,所以使用last.remove()并不是最有效的方法。相反,我建议你可以使用列表推导式来做类似下面的事情:

stop_words = set(["the", "of", "a", "to", "be", "from", "or"])
last = lower_words.split()
last = [word for word in last if word not in stop_words]

stop_words转换成一个集合是为了提高效率,但如果你把它保持为列表,效果也是一样的。

为了完整起见,这里是如何使用remove()来实现这个功能:

stop_words = ["the", "of", "a", "to", "be", "from", "or"]
last = lower_words.split()
for word in stop_words:
    try:
        while True:
            last.remove(word)
    except ValueError:
        pass

撰写回答