zoukankan      html  css  js  c++  java
  • 关于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:PythonwordcloudHiragino Sans GB.ttc'  # 路径不能有中文!
    41 
    42 wd = WordCloud(font_path=font, #   解决显示口字型乱码问题,
    43                # 可进入D:PythonwordcloudHiragino 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标志做的云词图片:

    字体包:

  • 相关阅读:
    响应式布局和BootStrap 全局CSS样式
    javascript中的undefined与null的区别
    before(),after(),prepend(),append()等新DOM方法简介
    解决文字和text-decoration:underline下划线重叠问题
    CSS3 linear-gradient线性渐变实现虚线等简单实用图形
    用Javascript获取页面元素的位置
    rem、px、em(手机端h5页面屏幕适配的几种方法)
    用flex和rem实现移动端页面
    HTML5新增的form属性简介(转载至张鑫旭)
    vue实现图片放大
  • 原文地址:https://www.cnblogs.com/pywjh/p/9382622.html
Copyright © 2011-2022 走看看