文件方式实现完整的英文词频统计实例
可以下载一长篇的英文小说,进行词频的分析。
1.读入待分析的字符串
2.分解提取单词
3.计数字典
4.排除语法型词汇
5.排序
6.输出TOP(20)
7.对输出结果的简要说明。
str=open('D:\\么么哒.txt','r') #读入待分析的字符串 str=str.read() #将所有大写转换为小写 str=str.lower() #将所有将所有其他做分隔符(,.?!)替换为空格 for i in ',.?!:': str=str.replace(i,' ') #分隔出一个一个单词 str=str.split(' ') #排除语法型词汇 exp={'is','and','that','it','a','our','have','','the','for','of','as','on','be','will','we','can','with','all','more','be','in','to','this','an','own','how','at','are','one'} word=set(str)-exp #计数字典 dic={} for i in word: dic[i]=str.count(i) str=list(dic.items()) #排序 str.sort(key=lambda x:x[1],reverse=True) for i in range(10): print(str[i])
结果:
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
==== RESTART: C:/Users/asus/AppData/Local/Programs/Python/Python36/666.py ====
('cut', 5)
('\n', 5)
('price', 5)
('gas', 5)
('natural', 4)
('\nthe', 3)
('use', 3)
('costs', 3)
('yuan', 3)
('said', 3)
>>>
说明:中国将降低非居民用户的天然气价格以减轻下游企业经营者的负担。

浙公网安备 33010602011771号