該案例以莎士比亞的四大悲劇之一《哈姆雷特》為例,來統計該文章中的詞語出現的頻率??傮w的步驟為讀入文本,大小寫轉換,特殊字符轉換,分詞,詞頻統計,排序。通過觀察詞語頻率最高的幾個詞,我們大致可以了解該文章的主要內容。這一小節,我們沒有涉及到英文文章中去停用詞的操作。
停用詞:出現的頻率很高,但對文章表達主旨沒有太大影響的詞。在英文文章中,如:I, and, but, here, there, some之類的詞語等。
文檔鏈接:鏈接:https://pan.baidu.com/s/17ehiYKripA--noIjfFLBbQ
提取碼:yuhq
下面是英文詞頻統計的代碼示例:
#導入文本
f = open('./data/hamlet.txt','r')
txt = f.read()
print(txt)
#這里只打印部分內容
# 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
#將文本內容全部轉化為小寫格式
txt = txt.lower()
#將特殊字符轉化為空格
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch,' ')
#以空格為分隔符,取出所有單詞
words = txt.split()
print(words)
#['the','tragedy','of','hamlet','prince','of'......]
#查看詞語的數量
len(words)
#32259
#查看無重復單詞的數量
len(set(words)) #set()函數的功能就是去除序列中的重復元素
#4793
#統計詞語的頻率
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
#將統計得到的字典counts轉換為列表
counts = list(counts.items())
print(counts)
#[('the', 1138),('tragedy', 3),('of', 669),('hamlet', 462),('prince', 10)......]
#對counts列表按照詞云頻率進行排序
counts.sort(key = lambda x:x[1],reverse = True)
#打印頻率最高的前10個詞語
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
由于我們沒有做去停用詞操作,從我們打印的前10個詞語中可以看出,the, and, to, of, you等這些對文章主旨影響不大的詞的頻率最高。這也符合我們的常識,任何一篇文章中出現最多的都是這些詞。