如何使用python来实现个性化词云的示例代码分享

如题所述

# coding=utf-8
# using python27
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

# d = path.dirname(__file__)

# Read the whole text.
text = open(r'C:\Study\Python\wordcloud_\alice.txt').read()

# read the mask / color image taken from
http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010
alice_coloring = np.array(Image.open(r'C:\Study\Python\wordcloud_\alice_color.png'))
stopwords = set(STOPWORDS)
stopwords.add("said")

wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
               stopwords=stopwords, max_font_size=40, random_state=42)
# generate word cloud
wc.generate(text)

# create coloring from image
image_colors = ImageColorGenerator(alice_coloring)

# show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.figure()
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
plt.axis("off")
plt.show()

执行这个代码还需要两个文件, 百度知道不能上传, 可以用扣或者私我传给你

运行结果:

温馨提示:答案为网友推荐,仅供参考
相似回答