马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# 文本词频统计
# HamletV1:找一个哈姆雷特的文件,保存为hamlet.txt,放在同一目录里面def getText(filename):
txt = open(filename, "r").read()
txt = txt.lower()
for ch in '!@#$%^&*+-()[]{}<>=_:;\\‘’"|~.':
txt = txt.replace(ch, " ")
return txt
f_name = "hamlet.txt"
hamletTxt = getText(f_name)
words = hamletTxt.split()
counts = {}
for word in words:
# word之前没有则创建初始值为0,然后逐次加1
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
# 将出现次数最多的前十个词输出
for i in range(10):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
|