我有下面的代码,我正在尝试将停止词列表应用于单词列表。然而,结果仍然显示了一些单词,如“a”和“the”,我认为这些单词会被这个过程删除。如果你有什么问题的话,那就太好了。
import nltk
from nltk.corpus import stopwords
word_list = open("xxx.y.txt", "r")
filtered_words = [w for w in word_list if not w in stopwords.words('english')]
print filtered_words
最佳答案
一些值得注意的事情。
如果你要一次又一次地对照一个列表检查成员资格,我会使用集合而不是列表。stopwords.words('english')
返回小写停止词列表。很可能您的来源中有大写字母,因此不匹配。
您没有正确读取文件,正在检查文件对象,而不是按空格拆分的单词列表。
把它们放在一起:
import nltk
from nltk.corpus import stopwords
word_list = open("xxx.y.txt", "r")
stops = set(stopwords.words('english'))
for line in word_list:
for w in line.split():
if w.lower() not in stops:
print w