Python制作词云的方法

yipeiwu_com5年前Python基础

需求:

看到朋友圈有人发词云照片,感觉自己也可以玩一玩,于是乎借助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

# import
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS

# current path
d = path.dirname(__file__)

# Read the whole text.
text = open(path.join(d, 'test.txt')).read()

# read the mask image
test_mask = np.array(Image.open(path.join(d, "test_mask.png")))

stopwords = set(STOPWORDS)
stopwords.add("said")

# setting
wc = WordCloud(background_color="black", max_words=2000, mask=test_mask,
        stopwords=stopwords)

# generate word cloud
wc.generate(text)

# plot and show
plt.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 file
wc.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.写的第一篇文章,不足之处欢迎来喷,毕竟我是要学习的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

元组列表字典(莫烦python基础)

Tuple 叫做 tuple,用小括号、或者无括号来表述,是一连串有顺序的数字。 a_tuple = (12, 3, 5, 15 , 6) another_tuple = 12,...

python查看FTP是否能连接成功的方法

本文实例讲述了python查看FTP是否能连接成功的方法。分享给大家供大家参考。具体如下: #!/usr/local/bin/python #-*- coding: UTF-8 -*...

一个基于flask的web应用诞生(1)

一个基于flask的web应用诞生(1)

基于flask的web应用的诞生,供大家参考,具体内容如下 Flask是一个非常优秀的web框架,它最大的特点就是保持一个简单而易于扩展的小核心,其他的都有用户自己掌握,并且方便替换,...

pygame实现弹力球及其变速效果

本文实例为大家分享了pygame实现弹力球及其变速效果的具体代码,供大家参考,具体内容如下 期望: 1.球体接触到框体后反弹 2.设置速度按键,按下后改变球体速度、颜色状态 具体实现:...

Python random模块常用方法

复制代码 代码如下: import random print random.random() 获取一个小于1的浮点数 复制代码 代码如下: import random random.r...