from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# 设置云词参数
font_path = 'msyh.ttc' # 字体文件路径
background_color = 'white' # 背景颜色
width = 1080 # 图片宽度
height = 1920 # 图片高度
max_words = 100 # 最大词数
mask = np.array(Image.open('mask.png')) # 词云形状
# 输入文字数组
text = ['Python', 'WordCloud', 'Matplotlib', 'Numpy', 'PIL', 'Image', 'Mask']
# 生成云词
wordcloud = WordCloud(font_path=font_path, background_color=background_color, width=width, height=height, max_words=max_words, mask=mask).generate(' '.join(text))
# 显示云词
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
# 保存云词图片
wordcloud.to_file('wordcloud.png')
代码使用了WordCloud库来生成云词,需要先安装该库。同时,需要将字体文件和词云形状文件放在代码所在的目录下,并将文件名修改为msyh.ttc
和mask.png
。最终生成的云词图片为wordcloud.png
。