孔明

python day 17 文本词频统计

牧云@^-^@ 提交于 2019-12-29 02:19:25
文本词频统计 一、概述 1.需求:一篇文章,出现了哪些词?哪些词出现得最多? 2.首先,要知道英文文本和中文文本的词频统计是不同的 二、“HAMLET” 1.噪音处理:提取单词,去除不必要的其他东西。 2.提取单词,split按空格切分,形成列表 3.统计单词和对应的词频,使用字典 4.词频按关键字:出现次数 排序,使用列表sort method 5.输出 Hamlet def gettext(): text = open("hamlet.txt",'r').read() text = text.lower() for ch in '"#$%^&*()_+-,./<>=@{}[]~'': text = text.replace(ch,'') return text hamlettext = gettext() words = hamlettext.split() counts = {} for word in words: counts[word]=counts.get(word,0)+1 items = list(counts.items()) items.sort(key = lambda x:x[1],reverse = True) for i in range (20): word,count = items[i] print("{0:<10}{1:>5}".format