温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

用python创建词云图片的方法

发布时间:2020-07-16 13:57:33 来源:亿速云 阅读:149 作者:清晨 栏目:编程语言

这篇文章主要介绍用python创建词云图片的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

Python实现词云的库有很多,较为常见的就是wordcloud,这个库基于PIL,PIL是必不可少的,需要用的还有matplotlib和numpy。

本文使用解释器为python2.7.13 32位。

安装

pip install wordcloud

使用

针对库示例做了一个简单修改,直接使用generate_from_frequencies方法,而没有使用generate()方法。有这样几个原因,generate_from_frequencies是基础的方法,generate()仍然还是要调用generate_from_frequencies方法;实验比较直接。

库的使用方法很简单,但是中文使用的话会有几个问题,一个是字符编码问题,二是字体问题,默认的字体不支持中文,因此需要加入font_path = "simfang.ttf"指定字体,这是把字体指定为同一个文件夹下的simfang.ttf。

示例:

#encoding=utf-8
from os import path
from wordcloud import WordCloud
import sys
reload(sys)
sys.setdefaultencoding('utf-8')


fre={"哈哈".decode('utf-8'): 1.2,"呵呵".decode('utf-8'):6}
wordcloud = WordCloud(font_path = "simfang.ttf").generate_from_frequencies(fre)

import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

效果如下:

用python创建词云图片的方法

先抽取网页的文本,然后再进行分词,将分词结果根据频率作为字典传给generate_from_frequencies,生成词云。
更简单,比如直接抽取文章的关键词,比如博客每篇文章就有关键词,用Counter库,直接生成频率调用。

使用背景图片生成词云

用python创建词云图片的方法

对上面的代码做了一点简单的改动:

#encoding=utf-8

from os import path
from wordcloud import WordCloud
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

d = path.dirname(__file__)
text = open(path.join(d, 'constitution.txt')).read().decode('utf-8')

import numpy as np
from PIL import Image
football = np.array(Image.open(path.join(d, "timg.jpg")))

fre={"哈哈".decode('utf-8'): 1.2,"呵呵".decode('utf-8'):6,"咯咯".decode('utf-8'):6,
"呵呵".decode('utf-8'):6,"咯咯".decode('utf-8'):6,
"啦啦".decode('utf-8'):1,"哦哦".decode('utf-8'):6,
"恩恩".decode('utf-8'):3,"呃呃".decode('utf-8'):6,
"饿饿".decode('utf-8'):3,"嗯嗯".decode('utf-8'):6,
"哼哼".decode('utf-8'):5,"丽丽".decode('utf-8'):6,
"咔咔".decode('utf-8'):7,"咳咳".decode('utf-8'):6,
"乐乐".decode('utf-8'):6,"呐呐".decode('utf-8'):6,
"嘎嘎".decode('utf-8'):6,"嘻嘻".decode('utf-8'):6}
#wordcloud = WordCloud(font_path = "simfang.ttf").generate(text)
wordcloud = WordCloud(font_path = "simfang.ttf",mask=football).generate_from_frequencies(fre)

import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

效果如下:

用python创建词云图片的方法

以上是用python创建词云图片的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI