2019-05-20 13:57:03 1452浏览
今天千锋扣丁学堂Python培训老师给大家分享一篇关于python统计文本中单词出现频率的具体代码,下面我们一起来看一下吧。#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()
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))
首先在和程序所在路径下创建几个文本文件,我建了两个,文件内容分别为hellopythongoodbyepython和ilikepython。运行程序,得到以下结果
【关注微信公众号获取更多学习资料】 【扫码进入Python全栈开发免费公开课】