python - 歌词词云2

接上文生成词云1
采用不同的底图,效果也不一样
好用的png图片网站

(https://pngimg.com/image)

关键在设置词云图的参数mask与img,设定img为'D:/cat.png'且mask设为img。
词云效果如下

"""制作词云图"""
# 读取图像
img = imageio.imread('D:/cat.png')
# img = Image.open('D:/cat.png')

# 设置词云图
wc = wordcloud.WordCloud(
    # width=1000, # 词云图的宽
    # height=700, # 图片的高
    background_color= 'black', # 词云图背景颜色
    font_path='msyh.ttc',  # 词云字体, 微软雅黑, 系统自带
    scale=10, # 字体大小
    mask=img,
    stopwords=set([line.strip() for line in open('cn_stopwords.txt', mode='r',
                                                 encoding='utf-8').readlines()])
)

from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 构建词云对象
wordcloud = WordCloud(width=800, height=800, background_color='white', font_path='msyh.ttc',
                      min_font_size=10, max_words=200)

# 读入文本文件
with open('G:/lyric/test/仗剑.txt', 'r') as f:
    text = f.read()

# 生成词云图像
wordcloud.generate(text)

# 显示词云图像
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)

# 保存词云图像
wordcloud.to_file("G:/d.png")

# 导入必要的库
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import imageio  # 图像模块

img = imageio.imread('D:/cat.png')
# 构建词云对象
wordcloud = WordCloud(width=800, height=800, background_color='white', font_path='msyh.ttc',mask=img,
                      min_font_size=10, max_words=200)

# 读入文本文件
with open('G:/lyric/test/仗剑.txt', 'r') as f:
    text = f.read()

# 生成词云图像
wordcloud.generate(text)

# 显示词云图像
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad=0)

# 保存词云图像
wordcloud.to_file("G:/d2.png")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容