import matplotlib.pyplot as plt# 示例文本text = "This is a simple example showing how to generate a word cloud using the generate method. Generate method uses the input text directly."# 创建WordCloud对象wordcloud = WordCloud(width=800, height=800, max_words=100, background_color='white').generate(text)# 显示词云plt.figure(figsize=(8, 8), facecolor=None)plt.imshow(wordcloud)plt.axis("off")plt.tight_layout(pad=0)plt.show()
import matplotlib.pyplot as plt# 示例文本text = "This is a simple example showing how to generate a word cloud using the generate method. Generate method uses the input text directly."# 创建WordCloud对象wordcloud = WordCloud(width=800, height=800, max_words=100, background_color='white').generate_from_text(text)# 显示词云plt.figure(figsize=(8, 8), facecolor=None)plt.imshow(wordcloud)plt.axis("off")plt.tight_layout(pad=0)plt.show()
复制代码
三、进阶技巧
1. 设置蒙版
蒙版设置, 设置蒙版之后, 词云的形状就会显示为设置的蒙版形状
from wordcloud import WordCloud
, ImageColorGeneratorimport matplotlib.pyplot as pltimport numpy as npfrom PIL import Imagemask_image = np.array(Image.open('./static/img.png'))# 示例文本text = "This is a simple example showing how to generate a word cloud using the generate method. Generate method uses the input text directly."# 创建WordCloud对象wordcloud = WordCloud(width=800, height=800, mask=mask_image, max_words=100, background_color='white')wordcloud.generate_from_text(text)# 显示词云plt.figure(figsize=(8, 8), facecolor=None)plt.imshow(wordcloud)plt.axis("off")plt.tight_layout(pad=0)plt.show()