在官方网站,有一个Alice的示例,准备好文件 alice.txt 和 alice_mask.png。

    1. from os import path
    2. from PIL import Image
    3. import numpy as np
    4. import matplotlib.pyplot as plt
    5. from wordcloud import WordCloud, STOPWORDS
    6. # Read the whole text.
    7. text = open('alice.txt').read()
    8. # read the mask image
    9. alice_mask = np.array(Image.open("alice_mask.png"))
    10. stopwords = set(STOPWORDS)
    11. stopwords.add("said")
    12. wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,
    13. stopwords=stopwords)
    14. # generate word cloud
    15. wc.generate(text)
    16. # store to file
    17. wc.to_file("alice.png")
    18. # show
    19. plt.imshow(wc, interpolation='bilinear')
    20. plt.axis("off")
    21. plt.figure()
    22. plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
    23. plt.axis("off")
    24. plt.show()

    词云官网示例 - 图1 词云官网示例 - 图2