Python 示例6 自定义词云图形状

Python生成指定形状词云图:这里引用《勇敢的心》经典台词,进行词云图生成展示。形状为抖音logo形状。

1410b024d4507d4dd7f7f5884eeee247.png

详细实现代码如下:

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()

后续公众号会发布系列教程,更多内容请关注公众号:程序猿学习日记 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值