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