用到的包:WordCould
环境:Python 3.8.2 或 PyCharm 2021.1.2 x64
输入下面命令行安装WordCould
pip install wordcloud
出现Successfully说明安装已成功
一、代码1
from wordcloud import WordCloud
wcd = WordCloud(background_color="white",repeat=True,max_words=200,width=1500,height=1000)
text="hello world python html css js java c++ c go "
wcd.generate(text)
wcd.to_file("test1.png")
test.png结果
但如果text内容是中文的话,就会出现下面的问题
输出的中文是混乱状态。
解决办法
加上font_path=“x”,x是中文的字体
x可以去C:\Windows\Fonts里面找,把找到的字体名字放到x的位置上即可
二、代码2(msyhbd.ttc是微软雅黑)
from wordcloud import WordCloud
wcd = WordCloud(background_color="white",repeat=True,max_words=200,width=1500,height=1000,font_path="msyhbd.ttc")
text="长沙 武汉 海口 上海 成都 北京 广州 深圳 三亚 厦门 西安 郑州"
wcd.generate(text)
#wcd.to_image()
wcd.to_file("test9.png")
效果1、微软雅黑
效果2、华文彩云
效果3、华文琥珀
如何在一个不规则的图形中生成彩云呢?
1、到入numpy和Image包
2、P一张目标图片(彩云会填充在黑色或其他颜色除了白色的位置)
三、代码3
from wordcloud import WordCloud
import numpy as np
from PIL import Image
mask = np.array(Image.open("boy1.png"))
wcd = WordCloud(background_color="white",repeat=True,max_words=800,width=1500,height=1000,font_path="msyhbd.ttc",mask=mask)
text="富强、民主、文明、和谐,自由、平等、公正、法治,爱国、敬业、诚信、友善"
wcd.generate(text)
#wcd.to_image()
wcd.to_file("test14.png")
boy1.png
test14.png
透明款(把背景设为None且加上一句mode=“RGBA”)
text为英文