2016-03-05 88 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)

相關問題