脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python jieba 中文分词与词频统计的操作

Python jieba 中文分词与词频统计的操作

2021-09-17 00:14方工 Python

这篇文章主要介绍了Python jieba 中文分词与词频统计的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

我就废话不多说了,大家还是直接看代码吧~


  1. #! python3
  2. # -*- coding: utf-8 -*-
  3. import os, codecs
  4. import jieba
  5. from collections import Counter
  6.  
  7. def get_words(txt):
  8. seg_list = jieba.cut(txt)
  9. c = Counter()
  10. for x in seg_list:
  11. if len(x)>1 and x != '\r\n':
  12. c[x] += 1
  13. print('常用词频度统计结果')
  14. for (k,v) in c.most_common(100):
  15. print('%s%s %s %d' % (' '*(5-len(k)), k, '*'*int(v/3), v))
  16.  
  17. if __name__ == '__main__':
  18. with codecs.open('19d.txt', 'r', 'utf8') as f:
  19. txt = f.read()
  20. get_words(txt)

样本:十九大报告全文


  1. 常用词频度统计结果
  2. 发展 ********************************************************************** 212
  3. 中国 ******************************************************** 168
  4. 人民 **************************************************** 157
  5. 建设 ************************************************* 148
  6. 社会主义 ************************************************ 146
  7. 坚持 ******************************************* 130
  8. 国家 ****************************** 90
  9. 全面 ***************************** 88
  10. 制度 *************************** 83
  11. 实现 *************************** 83
  12. 推进 *************************** 81
  13. 政治 ************************** 80
  14. 社会 ************************** 80
  15. 特色 ************************** 79
  16. 加强 *********************** 71
  17. 体系 ********************** 68
  18. 文化 ********************** 66
  19. 我们 ********************* 64
  20. 时代 ********************* 63
  21. 必须 ******************** 61
  22. 经济 ******************* 59
  23. 伟大 ******************* 58
  24. 完善 ***************** 51
  25. 我国 **************** 50
  26. 推动 *************** 47
  27. 现代化 *************** 47
  28. 安全 *************** 46
  29. 更加 ************** 44
  30. 民主 ************** 44

补充:jieba读取txt文档并进行分词、词频统计,输出词云图

代码实现


  1. # 库的引用
  2. import jieba
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. from wordcloud import WordCloud
  6. #定义一个空字符串
  7. final = ""
  8. #文件夹位置
  9. filename = r"D:\python\pra\推荐系统1-500.txt"
  10.  
  11. #打开文件夹,读取内容,并进行分词
  12. with open(filename,'r',encoding = 'utf-8') as f:
  13. for line in f.readlines():
  14. word = jieba.cut(line)
  15. for i in word:
  16. final = final + i +" "

运行结果

Python jieba 中文分词与词频统计的操作


  1. # 图云打印
  2. word_pic = WordCloud(font_path = r'C:\Windows\Fonts\simkai.ttf',width = 2000,height = 1000).generate(final)
  3. plt.imshow(word_pic)
  4. #去掉坐标轴
  5. plt.axis('off')
  6. #保存图片到相应文件夹
  7. plt.savefig(r'D:\python\pra\6.png')

图云输出图

Python jieba 中文分词与词频统计的操作

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/onestab/article/details/78307765

延伸 · 阅读

精彩推荐