很多時候,需要通過一些預先定義的標準將可用文字分類為各種類別。 nltk
提供此類功能作為各種語料庫的一部分。 在下面的範例中,檢視電影評論語料庫並檢查可用的分類。
# Lets See how the movies are classified
from nltk.corpus import movie_reviews
all_cats = []
for w in movie_reviews.categories():
all_cats.append(w.lower())
print(all_cats)
當執行上面的程式時,我們得到以下輸出 -
['neg', 'pos']
現在看一下帶有正面評論的檔案的內容。這個檔案中的句子是標記化的,列印前四個句子來檢視樣本。
from nltk.corpus import movie_reviews
from nltk.tokenize import sent_tokenize
fields = movie_reviews.fileids()
sample = movie_reviews.raw("pos/cv944_13521.txt")
token = sent_tokenize(sample)
for lines in range(4):
print(token[lines])
當執行上面的程式時,我們得到以下輸出 -
meteor threat set to blow away all volcanoes & twisters !
summer is here again !
this season could probably be the most ambitious = season this decade with hollywood churning out films
like deep impact , = godzilla , the x-files , armageddon , the truman show ,
all of which has but = one main aim , to rock the box office .
leading the pack this summer is = deep impact , one of the first few film
releases from the = spielberg-katzenberg-geffen's dreamworks production company .
接下來,通過使用nltk
中的FreqDist
函式來標記每個檔案中的單詞並找到最常用的單詞。
import nltk
from nltk.corpus import movie_reviews
fields = movie_reviews.fileids()
all_words = []
for w in movie_reviews.words():
all_words.append(w.lower())
all_words = nltk.FreqDist(all_words)
print(all_words.most_common(10))
當執行上面的程式時,我們得到以下輸出 -
[(,', 77717), (the', 76529), (.', 65876), (a', 38106), (and', 35576),
(of', 34123), (to', 31937), (u"'", 30585), (is', 25195), (in', 21822)]