import wordcloud
c=wordcloud.WordCloud()
c.generate("wordcloud by python ")
c.to_file("pywordcloud.png")
词云生成步骤
分隔:以空格分隔单词
统计:单词出现次数并过滤(1-2个字母会被滤掉)
字体:根据统计配置字号
布局:颜色环境尺寸
c=wordcloud.WordCloud(参数) 配置对象参数
参数(像素) | 描述 |
---|
width(默认400px) | c=wordcloud.WordCloud(width=600) |
height(默认200px) | c=wordcloud.WordCloud(height=400) |
min_font_size(默认4号) | c=wordcloud.WordCloud(min_font_size=10) |
max_font_size(根据高度自动调节) | c=wordcloud.WordCloud(max_font_size=20) |
font_step(默认1,步长) | c=wordcloud.WordCloud(font_step=2) |
font_path(默认None,字体路径) | c=wordcloud.WordCloud(font_path="msyh.ttc") |
max_words(默认200,最大数量) | c=wordcloud.WordCloud(max_words=20) |
stop_words(指定去除单词的列表) | c=wordcloud.WordCloud(stop_words={"python"}) |
background_color(默认黑色,词云背景色) | c=wordcloud.WordCloud(background_color="red") |
Scale 默认值1。值越大,图像密度越大越清晰
mask参数自定义词云形状
from scipy.misc import imread
mk=imread("pic.png")
c=wordcloud.WordCloud(mask=mk)
numpy 多维数组运算
matplotlib 绘图与数据可视化
pillow 图片处理
wordcloud 词云制作
imageio 图像输入输出
jieba 中文分词
snownlp 中文情感和自然语言处理
itchat 微信好友抓取
政府工作报告词云
import wordcloud
f = open('政府工作报告.txt',encoding='utf-8')
txt = f.read()
w = wordcloud.WordCloud(width=1000,
height=700,
background_color='white',
font_path='msyh.ttc')
w.generate(txt)
w.to_file('Test1.png')
==wordcloud中文分词(适合中文词云)==
import jieba
import wordcloud
w = wordcloud.WordCloud(width=1000,
height=700,
background_color='white',
font_path='msyh.ttc')
txt = '由于Python语言的简洁性、易读性以及可扩展性, \
在国外用Python做科学计算的研究机构日益增多, \
一些知名大学已经采用Python来教授程序设计课程。 \
例如卡耐基梅隆大学的编程基础、 \
麻省理工学院的计算机科学及编程导论就使用Python语言讲授。'
txtlist = jieba.lcut(txt)
string = " ".join(txtlist)
w.generate(string)
w.to_file('Teste2.png')
自定义绘制指定形状的词云
import jieba
import wordcloud
from scipy.misc import imread
mask=imread("图片形状.png")
f = open('政府工作报告.txt',encoding='utf-8')
txt = f.read()
f.close()
w = wordcloud.WordCloud(width=1000,
height=700,
background_color='white',mask=mask,
font_path='msyh.ttc')
w.generate(" ".join(jieba.lcut(txt)))
w.to_file('Test1.png')
==勾勒词云轮廓==
import wordcloud
string = open('hamlet.txt').read()
import imageio
mk = imageio.imread("ren.png")
w = wordcloud.WordCloud(background_color="white",
mask=mk,
contour_width=1,
contour_color='steelblue'
w.generate(string)
w.to_file('p2.png')
==按模板自身颜色绘制词云==
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
text = open('alice.txt').read()
import imageio
mk = imageio.imread("alice.png")
wc = WordCloud(background_color="white",
mask=mk,)
wc.generate(text)
image_colors = ImageColorGenerator(mk)
fig, axes = plt.subplots(1, 3)
axes[0].imshow(wc)
axes[1].imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
axes[2].imshow(mk, cmap=plt.cm.gray)
for ax in axes:
ax.set_axis_off()
plt.show()
wc_color = wc.recolor(color_func=image_colors)
wc_color.to_file('out-alice.png')
