您的位置:首页 > 编程语言 > Python开发

python实现统计文本中单词出现的频率

2017-11-13 14:23 711 查看
#coding=utf-8
import os
from collections import Counter
sumsdata=[]
for fname in os.listdir(os.getcwd()):
if os.path.isfile(fname) and fname.endswith('.txt'):
with open(fname,'r') as fp:
data=fp.readlines()
fp.close()
sumsdata+=[line.strip().lower() for line in data]
cnt=Counter()
for word in sumsdata:
cnt[word]+=1
cnt=dict(cnt)
for key,value in cnt.items():
print(key+":"+str(value))

首先在和程序所在路径下创建几个文本文件,我建了两个,文件内容分别为hello python goodbye python 和 i like python。运行程序,得到以下结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python