利用jieba和wordcloud写政府工作报告的词云统计和显示

阅读: 评论:0

利用jieba和wordcloud写政府工作报告的词云统计和显示

利用jieba和wordcloud写政府工作报告的词云统计和显示

非科班小白,断断续续学习一些python相关的知识,做个简单记录,方便以后查阅,代码中的filename文件需要在py文件同一个文件夹内,另外chinamap这个图片也需要在同意文件夹内。图片需要白色背景

 

import jieba
from wordcloud import WordCloud
from scipy.misc import imread


###排除词库
excludes = ["我们"]


#打开读取关闭文件
filename = &#' #这里的filename是变量
file = open(filename,"r",encoding="utf-8") 
txt = ad()
file.close()

#分词,jieba返回的是列表类型,所以words是一个列表
words = jieba.lcut(txt)

###词频统计,计数
counts={}
for word in words:
    if len(word)==1:  #排除单个字符的分词结果
        continue
    elif word in counts: 
        counts[word] = counts[word] + 1
    else:
        counts[word] = 1
'''
#或者elif和else可以用下列简短形式表达
    else:
        counts[word] = (word,0) + 1 #的形式简洁表示
'''

###排除出现在excludes列表里的词库
for word in excludes:
    del(counts[word])


#从高到低进行排序
items = list(counts.items()) #将字典转换为记录列表
items.sort(key=lambda x:x[1],reverse=True) #以第2列排序

#打印前n名高频词
for i in range(10): #这里的10是变量,可以根据需要调整
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

###词云制作及图片输出---普通模式
newtxt = " ".join(words) #用空格将分词的列表进行拼接,形成一个新的文本
w = WordCloud(font_path = &#",
              width = 1000,
              height = 700,
              background_color = "white",
              stopwords = excludes,
              ) #对WordCloud建立参数
w.generate(newtxt)
w.to_file("gr2018txt.png")


###以白色背景的图片为框架,引入形状的词云显示画面
img = 'chinamap.jpg'
mask = imread(img)

newtxt = " ".join(words) #用空格将分词的列表进行拼接,形成一个新的文本
w = WordCloud(font_path = &#",
              width = 1000,
              height = 700,
              background_color = "white",
              stopwords = excludes,
              mask = mask
              ) #对WordCloud建立参数
w.generate(newtxt)
w.to_file("gr2018img.png")

本文发布于:2024-02-02 10:27:15,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170684083643192.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23