统计文档中前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

猜你喜欢

转载自www.cnblogs.com/huigebj/p/11433878.html