[社团课L1] 数据可视化——词云
词云是文本大数据可视化的重要方式,可以将大段文本中的关键语句和词汇高亮展示。
以上为用福建师大附中的百度百科词条文本做的词云;
一.下载第三方库:wordcloud
pip install wordcloud
二.最简单的四行词云
- 词云1:《肖申克的救赎》:Hope is a good thing, maybe the best of things and no good thing ever dies!
import wordcloud
w = wordcloud.WordCloud() #创建wordcloud对象
w.generate('Hope is a good thing, maybe the best of things and no good thing ever dies! ')
w.to_file('output1.png') #把完成的词云图片保存为output1.png文件
运行代码,可在代码保存的文件夹下找到名为output1.png
的图片,即为上图;
可以发现WordCloud并不会用上所有字符,它会选出重要的词,并按出现次数多少来设置字体的大小,随机放置成一张词云;
三.添加参数
- 词云2:词云1的升级版
import wordcloud
w = wordcloud.WordCloud(width = 1000,
height = 700,
background_color = 'white')
w.generate('Hope is a good thing, maybe the best of things and no good thing ever dies!')
w.to_file('output2.png')
在创建wordcloud对象时,增加了一些参数,例如width
宽height
高,和background_color
背景颜色。
运行结果如下:
更多常见参数:
-
width 词云图片宽度,默认400像素;
-
height 词云图片高度,默认200像素;
-
background_color 词云图片的背景颜色,默认为黑色,传入‘’包围的颜色英语单词;
-
font_step 字号增大的梯度,默认1号;
-
font_path 指定字体路径,默认None,如若词云中出现中文则需加上
font_path = 'msyh.ttc'
-
mini_font_size 最小字号,默认4号;
-
max_font_size 最大字号,根据高度自动调节;
-
max_words 最大词数,默认200;
-
stop_words 不显示的单词,如需屏蔽多个单词,可写为
stop_words={'dog','cat'}
; -
Scale 清晰度,默认值1,值越大,图像密度越大越清晰;
-
mask 指定词云形状图片,默认为矩形;
-
词云3:福建师大附中百度百科词条
显然百度百科词条文本非常长,直接放在代码中很不方便;先把词条文本复制到文件ansfun.txt
中,而后在程序中从文件中读取文本;
import wordcloud
w = wordcloud.WordCloud(background_color='white',
max_font_size=50,
scale=15,
font_path='msyh.ttc')
f = open('ansfun.txt',encoding='utf-8')
#txt文件中的内容为中文,需要加上encoding='utf-8'
txt = f.read()
w.generate(txt)
w.to_file('output3.png')
四.加入词云形状
- 词云4:圆形的福建师大附中百度百科词条
首先下载第三方库imageio:
pip install imageio
通过以下代码读入外部图片形状:
import wordcloud
import imageio
ma=imageio.imread('circle.jfif') #选用名为circle.jfif的图片作为词云形状
w = wordcloud.WordCloud(background_color = 'white',
max_font_size = 50,
scale = 15, #不加此参数得出的词云较模糊
mask = ma, #把提取的图片设为mask参数
font_path = 'msyh.ttc')
imagecol=wordcloud.ImageColorGenerator(ma)
f = open('ansfun.txt',encoding='utf-8')
txt = f.read()
w.generate(txt)
w.to_file('output4.png')
选择图片时尽量使用白底图片;
五.按模板着色
import wordcloud
import imageio
ma = imageio.imread('circle.jfif')
w = wordcloud.WordCloud(background_color = 'white',
max_font_size = 50,
scale = 15,
mask = ma,
font_path = 'msyh.ttc')
imagecol = wordcloud.ImageColorGenerator(ma)
f = open('ansfun.txt',encoding='utf-8')
txt = f.read()
w.generate(txt)
w_col = w.recolor(color_func = imagecol)
w_col.to_file('output5.png')
我也没想到我们学校百科词条里有这么多的“啊”;