思路:
1.通過jieba庫獲取所有詞語串列;
2.計算串列里出現詞語及其對應的詞頻,存盤在字典中;
3.對字典里的詞語按照頻次進行排列;
4.輸出頻次前十的詞語及其頻次;
jieba庫的安裝
需要cmd進入命令提示符視窗,輸入pip install jieba安裝即可
源代碼如下
import jieba # 呼叫jieba庫
f_name = '斗破蒼穹.txt' # 檔案地址
with open(f_name, encoding='utf-8')as a: # 將檔案放入a中
b = a.read() # 對檔案進行讀操作
words = jieba.lcut(b) # words是直接生成一個裝有詞的串列,即list
count = {} # 定義一個字典
for word in words: # 列舉在文章中出現的詞匯
if len(word) < 2: # 排除字長小于2的詞
continue
else: # 統計詞頻
count[word] = count.get(word, 0)+1
list1 = list(count.items()) # 將字典中的鍵值對轉化為串列
list1.sort(key=lambda x: x[1], reverse=True) # 對串列按照詞頻從大到小排列
for i in range(10):
word, number = list1[i] # 將串列中的word與number提取出來
print("關鍵字:{:-<10}頻次:{:+>8}".format(word, number)) # 輸出word與number值、
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/197674.html
標籤:其他
