在官方网站,有一个Alice的示例,准备好文件 alice.txt 和 alice_mask.png。
from os import pathfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as pltfrom wordcloud import WordCloud, STOPWORDS# Read the whole text.text = open('alice.txt').read()# read the mask imagealice_mask = np.array(Image.open("alice_mask.png"))stopwords = set(STOPWORDS)stopwords.add("said")wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,stopwords=stopwords)# generate word cloudwc.generate(text)# store to filewc.to_file("alice.png")# showplt.imshow(wc, interpolation='bilinear')plt.axis("off")plt.figure()plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')plt.axis("off")plt.show()
