2016-03-05 92 views
0

在使用NLTK的python中,如何找到按类别过滤的文档中非停用词的数量?计算NLTK语料库中的非停用词

我可以弄清楚如何获得按类别过滤的语料库中的单词,例如,所有在类别“新闻”棕色语料库中的词是:

text = nltk.corpus.brown.words(categories=category) 

而且分开我能弄清楚如何让所有的单词为特定文档例如所有在棕色语料库文档“cj47”的话来说就是:

text = nltk.corpus.brown.words(fileids='cj47') 

,然后我可以在结果循环和计数不属于禁用词如的话

stopwords = nltk.corpus.stopwords.words('english') 
for w in text:  
    if w.lower() not in stopwords: 
#found a non stop words 

但是,我怎么把它放在一起,以便我按类别过滤特定文档?如果我尝试同时指定一个类别和一个过滤器,例如

text = nltk.corpus.brown.words(categories=category, fields=’cj47’) 

我得到一个错误说:

ValueError: Specify fields or categories, not both 

回答

1
  1. 获取fileids的类别:

    fileids = nltk.corpus.brown.fileids(categories=category)

  2. 对于每一个文件,算上非禁用词:

    for f in fileids: words = nltk.corpus.brown.words(fileids=f) sum = sum([1 for w in words if w.lower() not in stopwords]) print "Document %s: %d non-stopwords." % (f, sum)

相关问题