|
|
from tkinter import Image
|
|
|
import numpy as np
|
|
|
from wordcloud import WordCloud
|
|
|
import matplotlib.pyplot as plt
|
|
|
from imageio import imread
|
|
|
from PIL import Image
|
|
|
import random
|
|
|
import os
|
|
|
|
|
|
def get_random_color(*args, **kwargs):
|
|
|
colors = ["rgb(255, 182, 193)", # 淡粉色
|
|
|
"rgb(173, 216, 230)", # 淡蓝色
|
|
|
"rgb(252, 210, 110)"] # 淡黄色
|
|
|
return random.choice(colors)
|
|
|
|
|
|
def pink_color_func(*args, **kwargs):
|
|
|
return "rgb(255, 182, 193)" # 淡粉色
|
|
|
|
|
|
def orange_color_func(*args, **kwargs):
|
|
|
return "rgb(252, 210, 110)" # 淡黄色
|
|
|
|
|
|
# 生成词云图,可以通过添加style参数选择不同的风格
|
|
|
def generate_wordcloud(text, font_path, width, height, style='basic'):
|
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
if style == 'basic':
|
|
|
image_path = os.path.join(current_dir, 'image', 'love.png')
|
|
|
mask = np.array(Image.open(image_path))
|
|
|
wordcloud = WordCloud(mask=mask, font_path=font_path, width=width, background_color='white', height=height).generate(text)
|
|
|
elif style == 'jiyi':
|
|
|
image_path = os.path.join(current_dir, 'image', 'ji1.png')
|
|
|
mask = np.array(Image.open(image_path))
|
|
|
wordcloud = WordCloud(mask=mask, color_func=pink_color_func, font_path=font_path, width=width, background_color='white', height=height).generate(text)
|
|
|
elif style == '537':
|
|
|
image_path = os.path.join(current_dir, 'image', '537.png')
|
|
|
mask = np.array(Image.open(image_path))
|
|
|
wordcloud = WordCloud(mask=mask, color_func=orange_color_func, font_path=font_path, width=width, background_color='white', height=height).generate(text)
|
|
|
elif style == 'family':
|
|
|
image_path = os.path.join(current_dir, 'image', 'family.png')
|
|
|
mask = np.array(Image.open(image_path))
|
|
|
wordcloud = WordCloud(mask=mask, color_func=get_random_color, font_path=font_path, width=width, height=height, background_color='white').generate(text)
|
|
|
else:
|
|
|
wordcloud = WordCloud(font_path=font_path, width=width, height=height, mode='RGBA', relative_scaling=0.5).generate(text)
|
|
|
|
|
|
# 显示词云
|
|
|
plt.figure(figsize=(10, 5))
|
|
|
plt.imshow(wordcloud, interpolation='bilinear')
|
|
|
plt.axis('off')
|
|
|
plt.show()
|
|
|
|
|
|
|