码迷,mamicode.com
首页 > 其他好文 > 详细

统计文档中前5个高频词个数并输出

时间:2019-08-30 11:25:09      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:bsp   中国   个数   key   int   增加   输出   mat   lis   

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

 

统计文档中前5个高频词个数并输出

标签:bsp   中国   个数   key   int   增加   输出   mat   lis   

原文地址:https://www.cnblogs.com/huigebj/p/11433878.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!