参考:https://blog.csdn.net/kun1280437633/article/details/89474284
1、前期步骤:
- 获得一份待分析的文本数据,使用jieba库将这些段落划分成词;
- 分词后,根据分词结果生成词云,使用wordcloud;
- 使用matplotlib进行展现;
#导入对应的库
import jieba
import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud
#导入文本数据并进行简单的文本处理
#去掉换行符和空格
text=open("./data/文本.txt",encoding='utf-8').read()
text=text.replace("\n","").replace("\u30000","")
#分词,返回结果是词的列表
text_cut=jieba.lcut(text)
text_cut=' '.join(text_cut)#用某个符号连接为字符串
#导入停词,用于去除文本中得到停词,如'啊','的'
stop_words=open("./data/stop_words.txt",encoding='utf8')
#生成词云
word_cloud=WordCloud(font_path="simsun.ttc",#设置词云字体
background_color="white",#词云图的背景颜色
mask=graph,#指定词云形状
collocations=False,#去掉重复词
stopwords=stop_words)#去掉的停词
word_cloud.generate(text_cut)
#运用matplotlib展现结果
plt.subplots(figsize=(12,8))
plt.imshow(word_cloud)
plt.axis("off")
plt.show()
参数名 | 数据类型 | 作用 | 备注 |
---|---|---|---|
font_path | string | 导入字体 | font_path=“黑体.ttf” |
width | int | 画布宽度 | 默认400 |
height | int | 画布高 | 默认200 |
prefer_horizontal | float | 词语水平方向排版出现的频率 | 默认为0.9 |
mask | nd-array or None | 如果参数为空,则使用二维遮罩绘制词云,如果非空,设置的宽高被忽略,以输入的遮罩形状绘制词云,除白色部分不被绘制,其余部分皆用于绘制 | 词云形状 |
scale | float | 按比例放大画布 | 默认为1 |
min_font_size | int | 显示的最小字体大小 | 默认为4 |
font_step | int | 字体步长,如果步长大于1,运算加快,但结果可能出现偏差 | 默认为1 |
max_words | number | 要显示的词的最大个数 | 默认200 |
stopwords | set of string or None | 设置需要屏蔽的词 | 如果为空,使用内置STOPWORDS |
backgroud_color | color value | 背景颜色 | 默认为black |
max_font_size | int or None | 显示最大字体的大小 | 默认为None |
mode | string | 当参数为RGBA且backgroud_color不为空时,背景为透明 | 默认为RGB |
relative_scaling | float | 词频和字体大小的关联性 | 默认为.5 |
color_func | callable | 生成新颜色的函数,如果为空则使用self.color_func | 默认为None |
regexp | string or None | 使用正则表达式分隔输入文本 | |
collocations | bool | 是否包括两个词的搭配 | false去掉重复词 |
colormap | string or matplotlib colormap | 给每个单词随机分配颜色,如果设定color_func则忽略该方法 | 默认为viridis |
WordCloud对象的函数
- fit_word(frequencies) 根据词频生成词云
- generate(text) 根据文本生成词云
- generate_from_frequencies(frequencies[,…]) 根据词频生成词云
- generate_from_text(text) 根据文本生成词云
- process_text(text) 将长文本分词并去除屏蔽词(只针对英文)
- recolor([random_state,color_func,colormap]) 对现有输出重新着色
- to_array() 转化为numpy array
- to_file(filename) 输出到文件图像文件
from wordcloud import ImageColorGenerator
#颜色函数的设计
def ranfom_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
#使用图片原色上色
image_colors=ImageColorGenerator(mask)
wc.recolor(color_func=image_colors)