在文本處理期間經(jīng)常需要計(jì)算文本主體中單詞出現(xiàn)的頻率。 這可以通過應(yīng)用word_tokenize()函數(shù)并將結(jié)果附加到列表以保持單詞的計(jì)數(shù)來實(shí)現(xiàn),如下面的程序所示。
from nltk.tokenize import word_tokenize
from nltk.corpus import gutenberg
sample = gutenberg.raw("blake-poems.txt")
token = word_tokenize(sample)
wlist = []
for i in range(50):
wlist.append(token[i])
wordfreq = [wlist.count(w) for w in wlist]
print("Pairs\n" + str(zip(token, wordfreq)))
當(dāng)運(yùn)行上面的程序時(shí),我們得到以下輸出 -
[([', 1), (Poems', 1), (by', 1), (William', 1), (Blake', 1), (1789', 1), (]', 1), (SONGS', 2), (OF', 3), (INNOCENCE', 2), (AND', 1), (OF', 3), (EXPERIENCE', 1), (and', 1), (THE', 1), (BOOK', 1), (of', 2), (THEL', 1), (SONGS', 2), (OF', 3), (INNOCENCE', 2), (INTRODUCTION', 1), (Piping', 2), (down', 1), (the', 1), (valleys', 1), (wild', 1), (,', 3), (Piping', 2), (songs', 1), (of', 2), (pleasant', 1), (glee', 1), (,', 3), (On', 1), (a', 2), (cloud', 1), (I', 1), (saw', 1), (a', 2), (child', 1), (,', 3), (And', 1), (he', 1), (laughing', 1), (said', 1), (to', 1), (me', 1), (:', 1), (``', 1)]
條件頻率分布
當(dāng)想要計(jì)算滿足特定crteria滿足一組文本的單詞時(shí),使用條件頻率分布。
import nltk
#from nltk.tokenize import word_tokenize
from nltk.corpus import brown
cfd = nltk.ConditionalFreqDist(
(genre, word)
for genre in brown.categories()
for word in brown.words(categories=genre))
categories = ['hobbies', 'romance','humor']
searchwords = [ 'may', 'might', 'must', 'will']
cfd.tabulate(conditions=categories, samples=searchwords)
當(dāng)運(yùn)行上面的程序時(shí),我們得到以下輸出 -
may might must will
hobbies 131 22 83 264
romance 11 51 45 43
humor 8 8 9 13