用Python将上海疫情评论转成词云图,进行可视化呈现。
图片素材准备:
奉上代码:
# 导入模块
from wordcloud import WordCloud
from PIL import Image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 导入评论数据
df=pd.read_excel("上海疫情评论.xlsx")
text=' '.join(df.word.tolist())
text
# 词云图
font_path = 'C:/Windows/Fonts/SIMYOU.TTF' # 设置字体,可以显示中文
img = Image.open('胡萝卜.png') # 打开图片【此处可替换图片】
img_array = np.array(img) # 将图片装换为数组
# 设置停止词
stopwords = ''
# 配置词云的背景,图片,字体大小等参数
wc = WordCloud(
background_color='white', # 设置显示内容在什么颜色内
width=2000, # 设置图片宽,默认为400
height=2000, # 设置图片高,默认为200
mask=img_array, # 设置词云背景模板
font_path=font_path, # 设置字体路径
stopwords=stopwords, # 设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS
scale=1.5, # 图照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍
max_words=1000, # max_words图片上显示的最大词语的个数
max_font_size=120, # max_font_size为最大字体的大小
min_font_size=4, # min_font_size为最小字体大小,默认为4
mode='RGB', # ,默认值RGB,当参数为“RGBA”并且background_color不为空时,背景为透明
relative_scaling=.5, # 词频和字体大小的关联性,默认值
collocations=True # 是否包括两个词的搭配
)
wc.generate_from_text(text) # 根据文本生成词云
image_colors = ImageColorGenerator(img_array) # 获取color
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear") # 按照给定的图片颜色布局生成字体颜色,当wordcloud尺寸比image大时,返回默认的颜色
plt.axis('off') # 关闭坐标轴
plt.show() # 显示图片
wc.to_file('word_cloud_胡萝卜.png') # 保存图片
最终效果:
关注我,一起学习新知识吖~
一起学习的小伙伴如果有什么想法或者意见,欢迎沟通~