>>> 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']
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]
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]
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation
words = tokenize(text)
wordsWOStopwords = removeStopWords(words)
def tokenize(text):
sents = sent_tokenize(text)
return [word_tokenize(sent) for sent in sents]
def removeStopWords(words):
customStopWords = set(stopwords.words('english')+list(punctuation))
return [word for word in words if word not in customStopWords]
5 回答
我建议你创建自己的操作词单列表,你从禁用词列表中取出 . 可以方便地减去集合,因此:
然后你可以简单地测试一个单词是
in
还是not in
该集合,而不依赖于你的运算符是否是禁用词列表的一部分 . 然后,您可以稍后切换到另一个禁用词列表或添加运算符 .在_1387311中有一个内置的禁用词列表,由11种语言的2,400个停用词组成(Porter等),见http://nltk.org/book/ch02.html
我建议使用tf-idf来删除停用词,请参阅Effects of Stemming on the term frequency?
@ alvas的答案可以完成这项任务,但可以更快地完成 . 假设你有
documents
:一个字符串列表 .请注意,由于您在这里搜索集合(不在列表中),理论上速度理论上会快
len(stop_words)/2
倍,如果您需要通过许多文档操作,这很重要 .对于5000个大约300个单词的文档,我的例子为1.8秒,@ alvas为20秒 .
附:在大多数情况下,您需要将文本划分为单词以执行其他使用tf-idf的分类任务 . 所以最有可能的是使用stemmer也会更好:
并在循环内使用
[porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]
.@alvas有一个很好的答案 . 但同样取决于任务的性质,例如在您的应用程序中,您要考虑所有
conjunction
例如和,或者,但是,if,while和alldeterminer
,例如a,a,some,most,every,no作为停止词,将所有其他词性视为合法,那么你可能想要研究这个使用词性标注集来丢弃单词的解决方案,Check table 5.1:您可以将string.punctuation与内置的NLTK停用词列表一起使用:
NLTK关键字完成list