import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba,random
#编写设置词云字颜色函数
def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
h = random.randint(1, 250)
s = int(100.0 * 255.0 / 255.0)
l = int(100.0 * float(random.randint(60, 120)) / 255.0)
return "hsl({}, {}%, {}%)".format(h, s, l)
#步骤一 加载数据文件
file = open('data/text3.txt',mode='r')
text = file.read()
#步骤二 分词处理
wlist = jieba.cut(text,cut_all=True)
#连接字符创
wl = ' '.join(wlist)
#步骤三 创建词云对象(设置中文字体)
wd = WordCloud(background_color='white',max_font_size=500,min_font_size=3,width=1000,height=800,max_words=300,
font_path='data/simsun.ttc',margin=2,color_func = random_color_func)
#自动分词处理
res = wd.generate(wl)
#步骤三 显示词云
plt.figure()
#展示词云数据
plt.imshow(res)
#取消x,y轴标
plt.axis('off')
plt.show()