使用NLTK清除停用词

我试图通过使用nltk工具包删除停用词来处理用户input的文本,但与停止词删除像'和','或','不''被删除。 我希望这些词在停用词删除过程后出现,因为它们是以后处理文本作为查询所需的运算符。 我不知道在文本查询中哪些是可以作为操作符的词,我也想从我的文本中删除不必要的词。

我build议你创build自己的列表,从停用词列表中取出运算符字。 套可以方便地减去,所以:

operators = set(('and', 'or', 'not')) stop = set(stopwords...) - operators 

然后,您可以简单地testing单词是否in集合中,而不依赖于您的操作符是否是停用词列表的一部分。 稍后可以切换到另一个停用词列表或添加一个操作符。

 if word.lower() not in stop: # use word 

NLTK有一个内置的停止词表,由11种语言的2,400个停用词组成(Porter等人),参见http://nltk.org/book/ch02.html

 >>> from nltk import word_tokenize >>> from nltk.corpus import stopwords >>> stop = set(stopwords.words('english')) >>> sentence = "this is a foo bar sentence" >>> print([i for i in sentence.lower().split() if i not in stop]) ['foo', 'bar', 'sentence'] >>> [i for i in word_tokenize(sentence.lower()) if i not in stop] ['foo', 'bar', 'sentence'] 

我build议看看使用tf-idf删除停用词,请参阅词干频率的影响?

@阿尔瓦斯的答案是做这个工作,但它可以做得更快。 假设你有documents :一个string列表。

 from nltk.corpus import stopwords from nltk.tokenize import wordpunct_tokenize stop_words = set(stopwords.words('english')) stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation for doc in documents: list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] 

请注意,由于在这里您search的是一个集合(不在列表中),所以速度在理论上会是len(stop_words)/2倍,如果您需要通过许多文档进行操作,这是非常重要的。

对于大约300个字的5000个文档,每个差异在我的例子中是1.8秒,@ alvas是20秒。

PS在大多数情况下,您需要将文本分成单词以执行使用tf-idf的其他分类任务。 所以最有可能的是使用stemmer也会更好:

 from nltk.stem.porter import PorterStemmer porter = PorterStemmer() 

并在[porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]使用[porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

@alvas有一个很好的答案。 但是,这又取决于任务的性质,例如在你的应用程序中,你想要考虑所有的conjunction例如和,或者,但是,如果,当和所有的determiner例如,a,some,most,every,no作为停用词考虑到所有其他的词性都是合法的,那么你可能想看看这个使用词性标记集丢弃单词的解决scheme, 检查表格5.1 :

 import nltk STOP_TYPES = ['DET', 'CNJ'] text = "some data here " tokens = nltk.pos_tag(nltk.word_tokenize(text)) good_words = [w for w, wtype in tokens if wtype not in STOP_TYPES]