利用Python 統計txt 文檔詞頻 次數


-- coding:utf-8 --

import jieba

讀取文件

f=open(r'E:\Chrome_download\tieba.txt',encoding='utf-8')
txt =f.read()

print(txt)

分詞

words = jieba.lcut(txt)
string = ' '.join(words)

print(words)

print(f"輸出詞數量:{len(words)}") # 詞數量
print(f"不重復詞數量{len(set(words))}") # 不重復詞數量

構造詞頻字典

counts ={}
for word in words:
if len(word)==1:
continue
else:
counts[word]=counts.get(word,0)+1 # 這個語法需要理解下

    # dict.get(key,default=None)
    # key -- 字典中要查找的鍵
    # default 指定key不存在時,返回值。
    #

print(counts) # 輸出構造好的字典

轉列表

items = list(counts.items()) #返回可遍歷的(鍵, 值) 元組數組。

print(items)

排序

items.sort(key=lambda x:x[1],reverse=True)

print(items)

輸出前15個

for i in range(15):
word ,count = items[i]
print(f"{word}--出現了--{count}-次")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM