如何在Python中使用wordcloud库生成文字云?
一、安装和导入wordcloud库
在使用wordcloud前,需要保证库已经安装并导入:
!pip install wordcloud
from wordcloud import WordCloud
二、生成基本的文字云
首先,你需要提供一个文本文件,对于这个文件我们可以先完成以下几个步骤:
- 打开文件,并读取数据。
- 去除文件中的特殊符号和数字,只留下正常文字。
- 将文本序列转化为字符串形式。
代码实现如下:
import os
from collections import Counter
import jieba
text = open(os.path.join(d, 'news.txt')).read() #打开文件并读取数据
c = Counter(text) #可选:观察数据分布情况
list(filter(lambda x:x[1]>10,c.items())) #可选:去除较低频的词汇
text = ''.join(list(filter(lambda x:x[0] not in ',?!.;‘’“”‘’%1234567890',text))) #去除特殊符号和数字
text_cut = jieba.cut(text) #使用jieba库进行分词
text_cut = ' '.join(list(text_cut))
#生成文字云
wc = WordCloud(width=800,height=600,mode='RGBA',background_color=None).generate(text_cut)
wc.to_file("wordcloud.png")
运行程序,你将在当前目录下看到生成的”wordcloud.png”文件。
三、设计文字云的基本参数
wordcloud库提供了许多参数,可以对生成的文字云进行基础的调整。下面介绍几个常见的参数。
- background_color: 设定背景颜色,默认为黑色。
- width: 文字云的宽度,默认为400像素。
- height:文字云的高度,默认为200像素。
- max_words: 文字云中的最大词数,默认为200。
- font_path: 字体路径,用于设置字体。例如,’STHeiti Medium.ttc’ 或者 ‘/System/Library/Fonts/PingFang.ttc’
代码示例:
font_path = '/System/Library/Fonts/PingFang.ttc'
wc = WordCloud(
background_color='#E6E6FA',
width=800, height=600,
font_path=font_path,
max_words=500).generate(text_cut)
wc.to_file("wordcloud.png")
四、美化文字云
如果只是简单地生成文字云,效果往往不尽人意。接下来,我们可以从以下几个方面对文字云进行美化。
1. 修改字体颜色和形状
通过 WordCloud()实例中的 color_func 和 mask参数可以实现。
import numpy as np
from PIL import Image
mask = np.array(Image.open(os.path.join(d, "mask.png"))) # mask为透明png或JPEG图片
wc = WordCloud(
width=800, height=600,
max_words=400,
background_color=None,
mode='RGBA',
font_path=font_path,
mask=mask,
).generate(text)
def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
return "hsl(0, 0%%, %d%%)" % np.random.randint(60, 100)
wc.recolor(color_func=grey_color_func)
wc.to_file("wordcloud.png")
2. 调整字体大小
可以通过 WordCloud()实例中的relative_scaling参数调整。
relative_scaling:浮点数,按照词频调整字体大小。
wc = WordCloud(
background_color='#F0F8FF',
font_path=font_path,
width=800,height=600,
max_words=200,
relative_scaling=0.5
).generate(text_cut)
3. 自定义停用词
使用stopwords参数即可,其中每个元素用逗号分隔。
stopwords = set(jieba.cut(open(os.path.join(d, 'stopwords.txt')).read()))
wc = WordCloud(
background_color='#F0F8FF',
font_path=font_path,
width=800,height=600,
max_words=200,
relative_scaling=0.5,
stopwords=stopwords
).generate(text_cut)
五、总结
Python wordcloud库可以帮助我们生成精美的文字云,能够快速完成一些可视化的需求。我们可以根据实际情况,调整文字云的基本参数和美化参数,得到既美观又有意义的文字云。在生成文字云时,我们需要注意去除特殊符号和数字,保证展示的词汇具备可读性。同时也可以通过自定义停用词进行加强。最后,希望这篇关于wordcloud库的入门指南能够对你有所帮助。
原创文章,作者:XXOOI,如若转载,请注明出处:https://www.506064.com/n/375605.html