关于wordclou的一些简单操作

详细讲解一下怎么用python的三方库wordcloud制作一个关于歌曲《Vincent》的歌词,有特别背景的云词效果,如图所示:

首先的先准备好一张背景图,为了云词效果,可以实现修改一下,为了方便识别:

然后就是歌曲《Vincent》的txt文档,最好将他们放在一起(可以不用写路径),

如果需要输入路径,一定不能有中文!!会无法识别的

 然后就直接上代码:

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2018/7/27 18:20
 3 # @Author  : wjh
 4 # @File    : dpcq_yunci.py
 5 with open('Vincent.txt', 'w', encoding='utf-8') as f:
 6     f.write('''vincent—Starry night
 7 
 8 Starry starry night 
 9 paint your palette blue and grey 
10 look out on a summer's day 
11 with eyes that know the darkness in my soul 
12 
13 Shadows on the hills 
14 sketch the trees and the daffodils 
15 catch the breeze and the winter chills 
16 in colors on the snowy linen land 
17 
18 And now I understand 
19 what you tried to say to me 
20 and how you suffered for your sanity 
21 and how you tried to set them free 
22 They would not listen 
23 they did not know how 
24 perhaps they'll listen now ''')
25 
26 
27 import os
28 from wordcloud import WordCloud
29 from matplotlib import pyplot as plt
30 from PIL import Image
31 import numpy as np
32 
33 # 把图片变成矩阵的形式
34 mask = np.array(
35     Image.open(
36         os.path.join(
37             os.path.dirname(__file__),'景甜-(背景纯).png'))) # 注意修改自己图片的名字
38 
39 text = open('Vincent.txt', encoding='utf-8').read()
40 font = 'D:\Python\wordcloud\Hiragino Sans GB.ttc'  # 路径不能有中文!
41 
42 wd = WordCloud(font_path=font, #   解决显示口字型乱码问题,
43                # 可进入D:\Python\wordcloud\Hiragino Sans GB.ttc
44                # max_font_size=50, #最大字体设置
45                # max_words=400, # 最大词数
46                width=800,  # 画布宽度
47                height=400,  # 画布高度
48                margin=1,  # 字体之间宽度
49                mask=mask,  # 以该参数值作图绘制词云,
50                # 这个参数存在时,width和height会被忽略
51                background_color='black', # 背景颜色
52                random_state=42,  #设置有多少种随机生成状态,即有多少种配色方案
53                )
54 wd1 = wd.generate(text)
55 
56 # 将图片以“ceshi.png”文件保存
57 wd1.to_file('test.png')
58 # 开始绘制云图
59 plt.figure()
60 # 操作:加图片小标题
61 plt.title('Vincent 云词')  # 中文会乱码
62 # 操作:去掉x,y轴数值
63 plt.axis('off')
64 # 操作:显示图片
65 plt.imshow(wd)
66 # 展示给用户
67 plt.show()

编辑器里面显示如图:

代码中关于font的路径文件,是为了显示中文文字,比如用赵雷的《彩虹下面》,用的python标志做的云词图片:

字体包:

https://pan.baidu.com/s/1kq_7pcF6zQqbf4Uhiar4EA

猜你喜欢

转载自www.cnblogs.com/pywjh/p/9382622.html