Python生成指定形状词云图:这里引用《勇敢的心》经典台词,进行词云图生成展示。形状为抖音logo形状。
详细实现代码如下:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
# 文本地址
text_path = 'test.txt'
# 示例文本
scr_text = "Fight,and you may die." \
"Run,and you'll live at least a while." \
"And dying in your beds many years from now." \
"Would you be willing to trade?" \
"All the days from this day to that, " \
"for one chance,just one chance, " \
"to come back here and tell our enemies that they may take our lives, " \
"but they'll never take our Freedom!Freedom——"
# 保存示例文本
with open(text_path,'w',encoding='utf-8') as f:
f.write(scr_text)
# 读取文本
with open(text_path,'r',encoding='utf-8') as f:
# 这里text是一个字符串
text = f.read()
# 想生成带特定形状的词云,首先得准备具备该形状的mask图片
# 在mask图片中除了目标形状外,其他地方都是空白的
mask = np.array(Image.open("douyin.jpg"))
# 要跳过的词
stopwords = set(STOPWORDS)
# 去除better
stopwords.add("better")
# contour_width绘制mask边框宽度,contour_color设置mask区域颜色
# 如果mask边框绘制不准,设置contour_width=0表示不绘制边框
wc = WordCloud(background_color="white", max_words=2000, mask=mask,
stopwords=stopwords, contour_width=2, contour_color='red',scale=2,repeat=True)
# 生成图片
wc.generate(text)
# 存储文件
wc.to_file("result.png")
# 展示词云结果
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
# 展示mask图片
plt.imshow(mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()
后续公众号会发布系列教程,更多内容请关注公众号:程序猿学习日记