該案例以莎士比亞的四大悲劇之一《哈姆雷特》為例,來(lái)統(tǒng)計(jì)該文章中的詞語(yǔ)出現(xiàn)的頻率。總體的步驟為讀入文本,大小寫(xiě)轉(zhuǎn)換,特殊字符轉(zhuǎn)換,分詞,詞頻統(tǒng)計(jì),排序。通過(guò)觀察詞語(yǔ)頻率最高的幾個(gè)詞,我們大致可以了解該文章的主要內(nèi)容。這一小節(jié),我們沒(méi)有涉及到英文文章中去停用詞的操作。
停用詞:出現(xiàn)的頻率很高,但對(duì)文章表達(dá)主旨沒(méi)有太大影響的詞。在英文文章中,如:I, and, but, here, there, some之類(lèi)的詞語(yǔ)等。
文檔鏈接:鏈接:https://pan.baidu.com/s/17ehiYKripA--noIjfFLBbQ
提取碼:yuhq
下面是英文詞頻統(tǒng)計(jì)的代碼示例:
#導(dǎo)入文本
f = open('./data/hamlet.txt','r')
txt = f.read()
print(txt)
#這里只打印部分內(nèi)容
# The Tragedy of Hamlet, Prince of Denmark
# Shakespeare homepage | Hamlet | Entire play
# ACT I
# SCENE I. Elsinore. A platform before the castle.
# FRANCISCO at his post. Enter to him BERNARDO
#將文本內(nèi)容全部轉(zhuǎn)化為小寫(xiě)格式
txt = txt.lower()
#將特殊字符轉(zhuǎn)化為空格
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch,' ')
#以空格為分隔符,取出所有單詞
words = txt.split()
print(words)
#['the','tragedy','of','hamlet','prince','of'......]
#查看詞語(yǔ)的數(shù)量
len(words)
#32259
#查看無(wú)重復(fù)單詞的數(shù)量
len(set(words)) #set()函數(shù)的功能就是去除序列中的重復(fù)元素
#4793
#統(tǒng)計(jì)詞語(yǔ)的頻率
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
#將統(tǒng)計(jì)得到的字典counts轉(zhuǎn)換為列表
counts = list(counts.items())
print(counts)
#[('the', 1138),('tragedy', 3),('of', 669),('hamlet', 462),('prince', 10)......]
#對(duì)counts列表按照詞云頻率進(jìn)行排序
counts.sort(key = lambda x:x[1],reverse = True)
#打印頻率最高的前10個(gè)詞語(yǔ)
for i in range(10):
print(counts[i][0],counts[i][1])
# the 1138
# and 965
# to 754
# of 669
# you 550
# i 542
# a 542
# my 514
# hamlet 462
# in 436
由于我們沒(méi)有做去停用詞操作,從我們打印的前10個(gè)詞語(yǔ)中可以看出,the, and, to, of, you等這些對(duì)文章主旨影響不大的詞的頻率最高。這也符合我們的常識(shí),任何一篇文章中出現(xiàn)最多的都是這些詞。