python之生成词云(长恨歌)

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")

导出到图像文件

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值