美文网首页
使用wordcloud创建精美词云图片-day01

使用wordcloud创建精美词云图片-day01

作者: erisenlee | 来源:发表于2018-11-13 20:52 被阅读0次

  1. 首先安装需要使用的python库,最方便的方法就是使用 pip 工具
pip install wordcloud
pip install imageio
pip install matplotlib

说明: wordcloud 是主要的词云生成库,imageio是一个读写图片的io库,matplotlib是一个非常流行的数据可视化库

  1. 安装好必须的库之后,开始进入正式的代码编写
  • 首先导入库
import os
from os import path
from wordcloud import WordCloud
from imageio import imread
  • 接下来从文件中读取数据
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()

# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()
  • 创建wordcloud对象并从文件读取的数据生成词云图片
# Generate a word cloud image
wordcloud = WordCloud()
wordcloud.generate(text)
  • 将结果保存到文件
wordcloud.to_file(path.join(d,'simple.png'))

现在你可以在当前目录下发现一个simple.png图片,打开如下所示:

simple.png

相关文章

网友评论

      本文标题:使用wordcloud创建精美词云图片-day01

      本文链接:https://www.haomeiwen.com/subject/raxrfqtx.html