python之词云(wordcloud)
镜像下载:
pip install --index-url https://pypi.douban.com/simple wordcloud
wordcloud 库把词云当作一个WordCloud对象
- wordcloud.WordCloud()代表一个文本对应的词云
- 可以根据文本中词语出现的频率等参数绘制词云
- 绘制词云的形状、尺寸和颜色均可设定
- 以WordCloud对象为基础,配置参数、加载文本、输出文件
方法 | 描述 |
---|---|
w.generate() | 向WordCloud对象中加载文本txt w.generate(“Python and WordCloud”)` |
w.to_file(filename) | 将词云输出为图像文件,.png或.jpg格式 w.to_file(“outfile.png”)` |
配置对象参数
w= wordcloud.WordCloud(<参数>)
参数 | 描述 |
---|---|
width | 指定词云对象生成图片的宽度,默认400像素 w=wordcloud.WordCloud(width=600) |
height | 指定词云对象生成图片的高度,默认200像素 w=wordcloud.WordCloud(height=400) |
min_font_size | 指定词云中字体的最小字号,默认4号 w=wordcloud.WordCloud(min_font_size=10) |
max_font_size | 指定词云中字体的最大字号,根据高度自动调节 w=wordcloud.WordCloud(max_font_size=20) |
font_step | 指定词云中字体字号的步进间隔,默认为1 w=wordcloud.WordCloud(font_step=2) |
font_path | 指定文体文件的路径,默认None w=wordcloud.WordCloud(font_path="msyh.ttc") |
max_words | 指定词云显示的最大单词数量,默认200 w=wordcloud.WordCloud(max_words=20) |
stop_words | 指定词云的排除词列表,即不显示的单词列表 w=wordcloud.WordCloud(stop_words="Python") |
mask | 指定词云形状,默认为长方形,需要引用imread()函数 from scipy.msc import imread mk=imread("pic.png") w=wordcloud.WordCloud(mask=mk) |
background_color | 指定词云图片的背景颜色,默认为黑色 w=wordcloud.WordCloud(background_color="white") |
**实例:**制作长恨歌的词云
import wordcloud
import jieba
#读取文件
with open("./changhenge.txt",'r',encoding="utf-8") as fp:
st = fp.read()
result =jieba.lcut(st)
for i in result:
#把标点符号去掉
if i in ',。':
result.remove(i)
#把长度小于2的剔除
if len(i)< int(2):
result.remove(i)
#每个词之间用空格隔开
cloud = " ".join(result)
#设置参数属性,width图片长,height图片宽,font_path设置字体,background_color设置背景颜色
make_cloud = wordcloud.WordCloud(width=1000,
height=700,
font_path="msyh.ttc",
background_color="lightskyblue")
# 从文本生成词云
make_cloud.generate(cloud)
# 导出到图像文件
make_cloud.to_file("wordcloud1.png")