期末复习比较忙过段时间来专门写scrapy框架使用,今天介绍如何用python生成词云,虽然网上有很多词云生成工具,不过自己用python来写是不是更有成就感。
今天要生成的是励志歌曲的词云,百度文库里面找了20来首,如《倔强》,海阔天空是,什么的大家熟悉的。
所要用到的python库有 jieba(一个中文分词库)、wordcould 、matplotlib、PIL、numpy。
首先我们要做的是读取歌词。我将歌词存在了文件目录下励志歌曲文本中。
现在来读取他
1
2
3
4
5
|
#encoding=gbk lyric = '' f = open ( './励志歌曲歌词.txt' , 'r' ) for i in f: lyric + = f.read() |
加入#encoding=gbk是为了防止后面操作报错SyntaxError: Non-UTF-8 code starting with '\xc0'
然后我们用jieba分词来对歌曲做分词提取出词频高的词
1
2
3
4
5
6
|
import jieba.analyse result = jieba.analyse.textrank(lyric,topK = 50 ,withWeight = True ) keywords = dict () for i in result: keywords[i[ 0 ]] = i[ 1 ] print (keywords) |
得到结果:
然后我们就可以通过wrodcloud等库来生成词云了
首先先自己找一张图片来作为生成词云的形状的图
1
2
3
4
5
6
7
8
9
10
11
12
13
|
from PIL import Image,ImageSequence import numpy as np import matplotlib.pyplot as plt from wordcloud import WordCloud,ImageColorGenerator image = Image. open ( './tim.jpg' ) graph = np.array(image) wc = WordCloud(font_path = './fonts/simhei.ttf' ,background_color = 'White' ,max_words = 50 ,mask = graph) wc.generate_from_frequencies(keywords) image_color = ImageColorGenerator(graph) plt.imshow(wc) plt.imshow(wc.recolor(color_func = image_color)) plt.axis( "off" ) plt.show() |
保存生成图片
1
|
wc.to_file('dream.png') |
完整代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#encoding=gbk import jieba.analyse from PIL import Image,ImageSequence import numpy as np import matplotlib.pyplot as plt from wordcloud import WordCloud,ImageColorGenerator lyric = '' f = open ( './励志歌曲歌词.txt' , 'r' ) for i in f: lyric + = f.read() result = jieba.analyse.textrank(lyric,topK = 50 ,withWeight = True ) keywords = dict () for i in result: keywords[i[ 0 ]] = i[ 1 ] print (keywords) image = Image. open ( './tim.jpg' ) graph = np.array(image) wc = WordCloud(font_path = './fonts/simhei.ttf' ,background_color = 'White' ,max_words = 50 ,mask = graph) wc.generate_from_frequencies(keywords) image_color = ImageColorGenerator(graph) plt.imshow(wc) plt.imshow(wc.recolor(color_func = image_color)) plt.axis( "off" ) plt.show() wc.to_file( 'dream.png' ) |
以上这篇python生成词云的实现方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。