英文词云图
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
%matplotlib inline
df_train = pd.read_csv('./testporject/train.csv')
train_qs = pd.Series(df_train['question1'].tolist() + df_train['question2'].tolist()).astype(str)
cloud = WordCloud(width=1440, height=1080).generate(" ".join(train_qs.astype(str)))
plt.figure(figsize=(20, 15))
plt.imshow(cloud)
plt.axis('off')
下面以图片为背景,展示图片轮廓的云图
from PIL import Image
img = Image.open('./testporject/girl.png')
plt.imshow(img)
<matplotlib.image.AxesImage at 0x7fa9cc262ac8>
img_array = np.array(img)
cloud_m = WordCloud(width=1440, height=1080,mask = img_array).generate(" ".join(train_qs.astype(str)))
plt.figure(figsize=(20, 15))
plt.imshow(cloud_m)
plt.axis('off')
cloud_m.to_file('cloud.png')
下面是以图片背景颜色为字体颜色实现
image_colors = ImageColorGenerator(img_array) # 读取背景文件色彩
plt.figure(figsize=(20, 15))
plt.imshow(cloud_m.recolor(color_func=image_colors))
中文词云图
用到的文本CalltoArms.txt是鲁迅呐喊的节选。
import jieba
font = './testporject/FZSTK.TTF'
text = (open('./testporject/CalltoArms.txt','r',encoding='utf-8')).read()
cut = jieba.cut(text) #分词
string_ch = ' '.join(cut)
print(len(string_ch))
cloud_ch = WordCloud(width=1440, height=1080,
mask = img_array,
font_path=font).generate(string_ch)
plt.figure(figsize=(20, 15))
plt.imshow(cloud_ch)
plt.axis('off')
本文中用到的相关数据和图片链接: https://pan.baidu.com/s/1z-f8q6mIVTwK6AsERapWSw 提取码: d42x