統計文檔中前5個高頻詞個數並輸出


import jieba

ls="中國是一個偉大的國家,是一個好的國家"
print('原始文檔為:',ls)
counts={} # 定義統計字典
words=jieba.lcut(ls)
print('分好的詞組為:',words)

for word in words:
    counts[word]=counts.get(word,0)+1
print('生成的字典為:',counts)
print('字典的元素為:',counts.items())
#字典元組轉換為列表
items=list(counts.items())
print('counts的元素生成新的列表:',items)
#列表按第2個值進行排序-降序reverse=True,默認升序 
items.sort(key=lambda x:x[1],reverse=True)

print('按元組中第二維值排序后的列表為:',items)
#轉出列表前5個
for i in range(5):
    word,count=items[i]
    print("{0:<10}---{1:>5}".format(word,count))

#------------
for word in words:
    if len(word) ==1:   #增加一個判斷是否為詞組
        continue
    else:
        counts[word] = counts.get(word,0)+1

 


免責聲明!

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



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