python词云图之WordCloud

1. 导入需要的包package

import matplotlib.pyplot as plt
from scipy.misc import imread
from wordcloud import WordCloud,STOPWORDS
import xlrd

2. 设置生成词云图的背景图片,最好是分辨率高且色彩边界分明的图片

def set_background(picpath):
    back_coloring = imread(picpath)# 设置背景图片,png等图片格式
    return back_coloring

3. 创建词云图:WordCloud

def create_word_cloud(txt_str, back_coloring):  #txt_str表示导入的是字符串格式数据,#back_color表示的是背景图片位置
    print('---- 根据词频,开始生成词云! ----')
    font = r'C:\Windows\Fonts\simsun.ttc' #加载显示字体
    wc = WordCloud(
        font_path=font,
        collocations=False,  # 去重,如果不加,词云图会显示相同的词
        stopwords=STOPWORDS,  #加载停用词,如果不自己指定,则会加载默认的停用词
        max_words=100,
        width=2000,
        height=1200,
       # background_color='white',
       mask=back_coloring,
    )
    wordcloud = wc.generate(txt_str)
    # 写词云图片
    wordcloud.to_file(".\wordcloud_test.png")
    # 显示词云文件
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

4. 默认的停用词一般在:假如anaconda安装在D盘,则会在其目录:D:\Anaconda3\Lib\site-packages\wordcloud\stopwords,其中都是英文词,例如:

python词云图之WordCloudpython词云图之WordCloud

 

 注意:也可以在jieba分词中,先利用自己的停用词,得到去除停用词之后的文本字符串来绘制词云图:https://www.cnblogs.com/qi-yuan-008/p/11689530.html

5. 此时,词云图无法显示数字,这是因为 wc.generate 操作中,有去除数字的语句:在wordcloud.py中,第560行左右,所以想要显示数字,需要先注释这一行

python词云图之WordCloud

 

 6. 假设想要显示的词,已经经过jieba分词,保存在txt文档中,则绘制词云图的方法是:

例如:txt中是每行是一个词

python词云图之WordCloud

 

 则,先读取txt文件,形成字符串格式文本,再绘制

if __name__ == '__main__': 
    picpath = r".\xxx.png" #背景图片路径
    back_coloring = set_background(picpath)
    
    with open(r".\jieba_分词数据.txt", "r",encoding='utf-8') as f:
        remove_stop_str = f.read()
    
    create_word_cloud(remove_stop_str, back_coloring)

7. 如果通过jieba分词的数据已经处理成了(词, 词频)并保存在excel中,例如这种两列格式的excel表,第一行是标签如(词, 词频):

python词云图之WordCloud

 

则可以先读取词频再显示,python读取excel数据可以通过 xlrd.open_workbook 方法:

def read_from_xls(filepath,index_sheet):
    #读取文件名,filepath是excel文件的路径,index_sheet是第几个sheet
    #读取表格#
    # 设置GBK编码
    xlrd.Book.encoding = "gbk"
    rb = xlrd.open_workbook(filepath)
    print(rb)

    sheet = rb.sheet_by_index(index_sheet)
    nrows = sheet.nrows
    data_tmp = []

    for i in range(nrows - 1):
        tt=i+1  #excel的第一行是标签
        tmp_char = [str(sheet.cell_value(tt,0))] #第一列是词
        tmp_num = int(sheet.cell_value(tt,1))    #第二列是词频
        data_tmp.extend(tmp_char*tmp_num)
    return data_tmp

然后,读数据和生成词云图:

if __name__ == '__main__': 
    picpath = r".\xxx.png"
    back_coloring = set_background(picpath)
    
    data_dic = read_from_xls(r'D:\Python_workspace\spyder_space\jieba分词表.xlsx',0)
    data_dic_str = '\n'.join(data_dic)  #转成字符串格式
    
    create_word_cloud(data_dic_str, back_coloring)

8. 总结代码

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 10:47:17 2019

@author: Administrator
"""
import matplotlib.pyplot as plt
from scipy.misc import imread
from wordcloud import WordCloud,STOPWORDS
import xlrd

def set_background(picpath):
    back_coloring = imread(picpath)# 设置背景图片
    return back_coloring

def create_word_cloud(txt_str, back_coloring):
    print('---- 根据词频,开始生成词云! ----')
    font = r'C:\Windows\Fonts\simsun.ttc'
    wc = WordCloud(
        font_path=font,
        collocations=False,  # 去重
        stopwords=STOPWORDS,
        max_words=100,
        width=2000,
        height=1200,
       # background_color='white',
       mask=back_coloring,
    )
    wordcloud = wc.generate(txt_str)
    # 写词云图片
    wordcloud.to_file(".\wordcloud_test.png")
    # 显示词云文件
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

def read_from_xls(filepath,index_sheet):
    #读取文件名
    #读取表格#
    # 设置GBK编码
    xlrd.Book.encoding = "gbk"
    rb = xlrd.open_workbook(filepath)
    print(rb)

    sheet = rb.sheet_by_index(index_sheet)
    nrows = sheet.nrows
    data_tmp = []

    for i in range(nrows - 1):
        tt=i+1
        tmp_char = [str(sheet.cell_value(tt,0))]
        tmp_num = int(sheet.cell_value(tt,1))
        data_tmp.extend(tmp_char*tmp_num)
    return data_tmp

if __name__ == '__main__': 
    picpath = r".\xxx.png"
    back_coloring = set_background(picpath)
    data_dic = read_from_xls(r'D:\Python_workspace\spyder_space\jieba分词表.xlsx',0)
    data_dic_str = '\n'.join(data_dic)
    
#    with open(r".\jieba_分词数据.txt", "r",encoding='utf-8') as f: 
#    remove_stop_str = f.read()  

  create_word_cloud(data_dic_str, back_coloring) 

 

# 当然绘制词云图的方法有很多,这只是其中的一种

上一篇:词云摘抄


下一篇:7.19 wordcloud库的基本介绍