2019-05-20 13:57:03 2365瀏覽
今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于python統(tǒng)計文本中單詞出現(xiàn)頻率的具體代碼,下面我們一起來看一下吧。#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))
首先在和程序所在路徑下創(chuàng)建幾個文本文件,我建了兩個,文件內(nèi)容分別為hellopythongoodbyepython和ilikepython。運行程序,得到以下結(jié)果
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費公開課】
查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>