python学习笔记(三):使用jieba库进行文本词频统计

倖福魔咒の 提交于 2020-01-15 08:16:54

词频统计

从网上搜索下载若干篇中文或英文文本文件,编写Python程序代码,对下载的中英文文档分别进行词频统计(去除无关的构词,增添新创的构词),并对前20个频率最高的内容制作词云图。
停用词表 https://github.com/goto456/stopwords(如有特殊停用词也可自己添加修改)

可使用wordcloud库进行词云的绘制

jieba库常用函数

函数 描述
jieba.cut(s) 精确模式,返回一个可迭代的数据类型
jieba.cut(s, cut_all=True) 全模式,返回一个包括文本s中所有可能单词的可迭代数据类型
jieba.cut_for_search(s) 搜索引擎模式,适合搜索引擎建立索引的分词结果
jieba.lcut(s) 精确模式,返回一个列表类型,建议使用
jieba.lcut(s, cut_all=True) 全模式,返回一个列表类型,建议使用
jieba.lcut_for_search(s) 搜索引擎模式,返回一个列表类型,建议使用
jieba.add_word(w) 向分词词典中增加新词w

实例代码

import jiebaimport wordcloud
import pandas as pd
import matplotlib as plt

fname = input("请输入文件名:")
f = open(fname, 'r')
text = f.read()
f.close()

cut_text = jieba.lcut(text)#将原文件分为词语
f = open("停用词表.txt")#读取停用词
stop_words = "".join(f.read())
stop_words.join('\n\t')
f.close()

stop_words_list = stop_words.split('\n')
stop_words_list.append('\n')
filted_text_list = []
for s in cut_text:    
if s not in stop_words_list:        
	filted_text_list.append(s)
words_dic = {}
for s in filted_text_list:
    words_dic[s] = words_dic.get(s, 0) + 1#统计词频
words_list = list(words_dic.items())
words_list.sort(key=lambda x: x[1],reverse=True)

words_dic = dict(words_list)
cloud_words_list = list(words_dic.keys())
cloud_words = " ".join(cloud_words_list[:20])#取排名前二十的词语
wc=wordcloud.WordCloud(font_path="simhei.ttf", width=300, height=250, background_color="#ffffff", max_font_size=80, random_state=50, prefer_horizontal=0.9)
wc_im=wc.generate_from_text(cloud_words) 
wc_im.to_image().save("合肥市政府报告.jpg")
plt.pyplot.imshow(wc, interpolation="bilinear")

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!