如何將統計word文檔中的詞頻呢?先用docx模塊將word文檔轉變成txt格式,然後使用jieba模塊進行分詞,並統計詞頻。是不是很簡單~
#2020年3月10日
#Elizabeth
from docx import Document
import jieba #分詞模塊
#自定義函數,將word文檔寫入txt文檔
def to_txt(path):
document=Document(path)
txt=open('/Users/fangluping/Desktop/數據分析筆試試題/詞頻統計.txt','w+')
for paragraph in document.paragraphs:
text=paragraph.text
txt.write(text)
txt.close()
return txt
if __name__=='__main__':
path0='/Users/fangluping/Desktop/數據分析筆試試題/筆試題目-V1.0.docx'
to_txt(path0) #調用寫入txt文檔的函數
#分詞
txt=open('/Users/fangluping/Desktop/詞頻統計.txt','r',encoding='utf-8').read()
words=jieba.lcut(txt)
counts={}
for word in words:
if len(word)==1:
continue
else:
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))