wordcloud 库概述展开目录
wordcloud 是优秀的词云第三方库。词云以词语为基本单位,更加直观和艺术的展示文本
wordcloud 库的安装展开目录
windows 下在命令行输入
- pip install wordcloud
配置对象参数展开目录
- w = wordcloud.WorldCloud(<参数>) #创建wordcloud对象
参数 | 描述 |
---|---|
width | 指定词云对象生成图片的宽度,默认 400 像素 |
height | 指定词云对象生成图片的高度,默认 200 像素 |
min_font_size | 指定词云中字体的最小字号,默认 4 号 |
max_font_size | 指定词云中字体的最大字号,根据高度自动调节 |
font_step | 指定词云中字体字号的步进间隔,默认为 1 |
font_path | 指定字体文件的路径,默认为 None |
max_words | 指定词云显示的最大单词数量,默认 200 |
stop_words | 指定词云的排除词列表,即不显示的单词列表 |
mask | 指定词云形状,默认为长方形,需要引用 imread () 函数 |
background_color | 指定词云图片的背景颜色,默认为黑色 |
常用方法展开目录
方法 | 描述 |
---|---|
w.generate(txt) | 向 WordCloud 对象 w 中加载文本 txt |
w.to_file(filename) | 将词云输出为图像文件 |
政府工作报告词云展开目录
- from wordcloud import *
- from jieba import *
- f = open("新时代中国特色社会主义.txt","r",encoding = "utf-8")
- t = f.read()
- f.close()
- ls = lcut(t)
- txt = " ".join(ls)
- w = WordCloud(font_path = "msyh.ttc", width = 1000, height = 700, background_color = "white")
- w.generate(txt)
- w.to_file("test.png")
更有形的词云展开目录
给出一张中国地图,我们希望词云填充下面这张图中的非白色部分
- from wordcloud import *
- from jieba import *
- from scipy.misc import imread
- mask = imread("chinamap.png")
- f = open("新时代中国特色社会主义.txt","r",encoding = "utf-8")
- t = f.read()
- f.close()
- ls = lcut(t)
- txt = " ".join(ls)
- w = WordCloud(font_path = "msyh.ttc", mask = mask, width = 1000, height = 700, background_color = "white")
- w.generate(txt)
- w.to_file("test.png")