python哈姆雷特词频统计_人生苦短我用Python——哈姆雷特词频统计

在本文中利用Python对Hamlet英文词频进行统计,我们解决该问题的基本流程应该如下:

1、读取文件

2、将所有英文字母变成小写

3、根据标点符号,对!'#$%&()*+,-./:;<=>?@[\\]^_‘{|}~等对单词进行分割,形成列表

4、对每个单词进行计数

f1 = open("hamlet.txt",encoding="utf-8")

f2 = f1.read()

text = f2.lower()

str2 = "!'#$%&()*+,-./:;<=>?@[\\]^_‘{|}~"

text=list(text)

number=0

for each in text:

if each in str2:

text[number]=" "

number+=1

text = "".join(text)

word = text.split(" ")

dict1 = dict()

for each in word:

dict1[each] = dict1.get(each,0)+1

items = list(dict1.items())

items.sort(key=lambda x:x[1],reverse=True)

for i in range(100):

print(items[i])

得到结果:

('the', 44680)

你可能感兴趣的:(python哈姆雷特词频统计)