Python制作词云的方法
Python  /  管理员 发布于 7年前   162
需求:
看到朋友圈有人发词云照片,感觉自己也可以玩一玩,于是乎借助wordcloud实现功能。
环境:
MacOS 10.12 +Python 2.7 +Wordcloud
Windows通用
准备:
安装wordcloud
$ pip install wordcloud
SIP功能是Apple在OSX上推出的系统完整性保护功能,新版本的macOS直接用pip安装报错,在不关闭SIP功能的前提下,可以使用
$ pip install wordcloud --user -U
某些情况还会提示错误,需要安装VS for Python,直接上官网下载安装即可。
实现:
源码
#! /usr/bin/env python# importfrom os import pathfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as pltfrom wordcloud import WordCloud, STOPWORDS# current pathd = path.dirname(__file__)# Read the whole text.text = open(path.join(d, 'test.txt')).read()# read the mask imagetest_mask = np.array(Image.open(path.join(d, "test_mask.png")))stopwords = set(STOPWORDS)stopwords.add("said")# settingwc = WordCloud(background_color="black", max_words=2000, mask=test_mask, stopwords=stopwords)# generate word cloudwc.generate(text)# plot and showplt.imshow(wc, interpolation='bilinear')plt.axis("off")plt.figure()plt.imshow(test_mask, cmap=plt.cm.gray, interpolation='bilinear')plt.axis("off")plt.show()# store to filewc.to_file(path.join(d, "test.png"))
辅助文件
test_mask.png
test.txt
The list of big's prior run-ins with the far-right fringe is long and varied. He tweeted fake crime statistics spread by racists to paint black cans as violent, then defended them as credible. He sparked a firestorm last year when he declined to renounce
效果图
其它说明:
1.文档可以是任意英文txt文件,以上的是网络上英文新闻中的一小段,仅起示例作用。
2.关于中文支持,有多种方法,主要就是分词的问题,这里不讨论了。
3.我不清楚许多人说的定制是什么意思,因为如果想要自己任意想要的形状的话,我觉得用PS做一个png图可以达到同样的效果,经测试也没有发现问题。
4.写的第一篇文章,不足之处欢迎来喷,毕竟我是要学习的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号