# -*- coding:utf-8 -*-
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
import jieba
import numpy as np
from PIL import Image
import random
import jieba.analyse
def word_umaru1(path:"file"):#english text
text = open(path).read()
wc = WordCloud().generate(text)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic1.png")
def word_umaru2(path:"file"):#chinese text
text = open(path,encoding="utf-8").read()
wc = WordCloud(font_path='Hiragino.ttf', width=800, height=600, mode='RGBA', background_color=None).generate(text)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic2.png")
def word_umaru3(path:"file"):#jieba分词
text = open(path,encoding="utf-8").read()
text = ' '.join(jieba.cut(text))
wc = WordCloud(font_path="msyhbd.ttc",width=800,height=600,mode='RGBA',background_color=None).generate(text)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic3.png")
def word_umaru4(path:"file"):#mask遮罩
text = open(path,encoding="utf-8").read()
text = ' '.join(jieba.cut(text))
mask = np.array(Image.open("1.png"))
wc = WordCloud(mask=mask,font_path="msyhbd.ttc",mode='RGBA',background_color=None).generate(text)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic4.png")
def word_umaru5(path:"file"):#使用图片颜色
text = open(path,encoding="utf-8").read()
text = ' '.join(jieba.cut(text))
mask = np.array(Image.open("1.png"))
wc = WordCloud(mask=mask,font_path="msyhbd.ttc",mode='RGBA',background_color=None).generate(text)
image_colors = ImageColorGenerator(mask)
wc.recolor(color_func = image_colors)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic5.png")
def random_color(word,font_size,position,orientation,font_path,random_state):#自定义颜色
s = 'hsl(0, %d%%,%d%%)'%(random.randint(60,80),random.randint(60,80))
return s
def word_umaru6(path:"file")::#自定义颜色
text = open(path,encoding="utf-8").read()
text = ' '.join(jieba.cut(text))
mask = np.array(Image.open("1.png"))
wc = WordCloud(color_func=random_color,mask=mask,font_path="msyhbd.ttc",mode='RGBA',background_color=None).generate(text)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic6.png")
def word_umaru7(path:"file"):#分析词汇频率,使用图片颜色
text = open(path,encoding="utf-8").read()
freq = jieba.analyse.extract_tags(text,topK=200,withWeight = True)
freq = {i[0]:i[1] for i in freq}
mask = np.array(Image.open("color_mask.png"))
wc = WordCloud(mask=mask,font_path='Hiragino.ttf',mode='RGBA',background_color=None).generate_from_frequencies(freq)
image_colors = ImageColorGenerator(mask)
wc.recolor(color_func = image_colors)
plt.imshow(wc,interpolation = "bilinear")
plt.axis("off")
wc.to_file("pic7.png")
def main():
fig = plt.figure(figsize=(10,15))#创建多个子图
for i in range(1,8):
if i==1:
path = "ing.txt"
str_="word_umaru"+str(i)+"(path)"
else:
path = "xyj.txt"
str_="word_umaru"+str(i)+"(path)"
fig.add_subplot(2,4,i)
exec(str_)
fig.savefig("result.png")
plt.show()
main()