資源簡介
python使用jieba 分詞
代碼片段和文件信息
#打開“三國演義.txt”文件,讀取文件內容
import?jieba????????????????????????????????????#導入jieba分詞
f?=?open(“三國演義.txt“?“r“?encoding=‘utf-8‘)???#打開文件
txt?=?f.read()??????????????????????????????????#讀取文件內容
#分詞
words?=?jieba.lcut(txt)????????????????????????#將句子拆分為詞語保存到列表中
#統計
counts?=?{}?????????????????????????????????????#建立空字典,用于存儲詞和出現次數
for?word?in?words:?
????if?len(word)?==?1:??????????????????????????#單字的詞語忽略不計
????????continue
????else:
????????counts[word]?=?counts.get(word0)?+?1???#出現次數+1
#排序
items?=?list(counts.items())????????????????????#字典轉化為列表后才可以排序
items.sort(key?=?lambda?x:x[1]?reverse?=?True)?#對列表items按“次數”降序排序
#輸出前20個元素的值
for?i?in?range(20):?
????print?(items[i][0]?items[i][1])
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件??????????81??2020-04-22?07:50??三國演義.txt
?????文件?????????956??2020-04-22?07:43??sanguo.py
評論
共有 條評論