普通词云图
import requests
import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
plt.rcParams['font.sans-serif'] = ['SimHei'] #解决中文显示
plt.rcParams['axes.unicode_minus'] = False #解决符号无法显示
# 读取 Excel 文件
all_suggestions_df = pd.read_excel(r'D:\Desktop\aaa.xlsx')
# 假设你想要生成词云的文本在第一列
all_suggestions_text = ' '.join(all_suggestions_df.iloc[:, 0].astype(str))
wordcloud = WordCloud(font_path='msyh.ttc',
width=800,
height=400,
background_color='white').generate(all_suggestions_text)
# 显示图像
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.savefig(r'D:\Desktop\wordcloud.png', format='png')
plt.show()
自定义背景词云图
词云文件目录结构
----main.py python源代码
----stop.txt 过滤掉的词语
----simhei.ttf 字体格式文件
----text.txt 要生成词云图的txt文件
----001.png 背景图
Stop文件(过滤词将不想展示的词(文字,符号等都可以)放进去,一行添加一个)或者在Python文件stop这里添加
字体:可以在网上下载也可以复制本地的(从C\windows\Fonts里找喜欢的)
Text:你的文本文件
展示的单词数:
如只想展示最多出现的前二十个词
在这里直接输二十个就好啦
Ps处理图片
抠图,把你想要的形状扣出来然后将里面使用一种颜色填充只留轮廓,背景选白色,导出为png图片
Python源代码
import jieba
from wordcloud import WordCloud
import numpy as np
from PIL import Image
from matplotlib import colors
f = open(r'text.txt',"r",encoding="utf-8")
text = f.read()
f.close()
words_list_jieba = jieba.lcut(text)
def findifhave(demo,stop):
for ret in stop:
if(demo == ret):
return 'T'
stop = ['\n']
with open("stop.txt",'r',encoding='utf-8') as f1:
for line in f1:
stop.append(line.replace("\n",""))
f1.close()
dict = {}
for key in words_list_jieba:
dict[key] = dict.get(key,0) + 1
for demo in list(dict.keys()):
if('T' == findifhave(demo,stop)):
del dict[demo]
dict1 = sorted(dict.items(),key = lambda d:d[1] , reverse = True)
print(dict1)
background_image = np.array(Image.open('001.png'))
colormaps = colors.ListedColormap(['#871A84', '#BC0F6A', '#BC0F60', '#CC5F6A', '#AC1F4A'])
wordcloud = WordCloud(font_path='simhei.ttf', # 字体
prefer_horizontal=0.99,
background_color='white', # 背景色
max_words=20, # 显示单词数
max_font_size=400, # 最大字号
stopwords=stop, # 过滤噪声词
mask=background_image, # 背景轮廓
colormap=colormaps, # 使用自定义颜色
collocations=False
).fit_words(dict)
image = wordcloud.to_image()
image.show() # 展示图片
wordcloud.to_file('词云图.png') # 保存图片
效果图: