-- 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}-次")