python爬虫【1】——词云解释

 

需要的库:worldcloud 【词云库】jieba【分频字段】

介绍一下词云用法,看代码理解。网上很多人都介绍一点,会用但是不会系统的介绍这个库,在查看官方文档的时候在仔细的解释下。在代码中注释中文,每一个命令是做什么的。就当作学习一下如何看文档吧。

官方文档:worldcloud

1、API Reference

1.1 WordCloud(font_path, width, height, …)

后面跟的参数(font_path = Nonewidth = 400height = 200margin = 2ranking_only = Noneprefer_horizo​​ntal = 0.9mask = Nonescale = 1color_func = Nonemax_words = 200min_font_size = 4stopwords = Nonerandom_state = Nonebackground_color ='black'max_font_size = Nonefont_step = 1mode ='RGB'relative_scaling ='auto'regexp = Nonecollocations = Truecolormap = Nonenormalize_plurals = Truecontour_width = 0contour_color ='black'repeat = False )关于worldcloud 详细解释。

我只介绍常用的。

这个是 作用是生成和绘制词云。也是我们常用的。这个结构中包含的是一些词云的信息,字大小尺寸、字体、颜色、背景、选择的mask等等

worldcloud(font_path='词云字体路经',      #词云字体路经
            background_color = 'white',  #设置背景颜色
            mask = color_mask,            #这里一般会是一个图片,用来做为词云的框架
            max_words = 1000,             #显示的词的最大个数
            max_font_size = 100           #显示字体最大的尺寸
            random_state = 30             #有多少种配色
            ...
            ...
)

1.2、ImageColorGenerator(image, default_color=None)

这个是彩色图像的颜色生成器。即改变字体的颜色,根据图片创建颜色

1.3、random_color_func(word,font_size,...)

随机色调产生

 

2、Gallery of Examples

这里我只介绍两种常用的,一种是根据图片显示词云、一种是根据词频显示。具体的其他玩法看官方文档。词云的多种用法。

2.1 导入一张图片mask,显示词云

图片显示的代码较为简单,我们只需要把单词分好(这里涉及到NLP的文本更深的处理了),我们就针对词云来解释不做多余的设置。

import os 
from wordcloud import WordCloud
from scipy.misc import imread  
  

cut_text = open('E://pythonnotebook//text.txt', 'r').read()

color_mask = imread('E://pythonnotebook//cloud.jpg')  #设置背景图  
cloud = WordCloud(  
        font_path = 'simfang.ttf',   
        background_color = 'white',  
        mask = color_mask,  
        max_words = 1000,  
        max_font_size = 100          
        )  
word_cloud = cloud.generate(cut_text)  
# 保存词云图片  
word_cloud.to_file('word_cloud.jpg')  
plt.imshow(word_cloud)  
plt.axis('off')  
plt.show() 

2.2如何利用jieba库做词频的云图

这里简单介绍一下,如何利用jieba的分词功能,参考的博客jieba分词

  • 精确模式,试图将句子最精确地切开,适合文本分析;
  • 全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;
  • 搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。

.cut的模式中,默认是精准模式,但cut_all=ture为全模式,儿cut_all=false 为精准模式

.cut_for_search 搜索引擎模式。【等,jieba.lcut 以及 jieba.lcut_for_search 直接返回 list】

他们的结构返回的值都是一个可以迭代的generator

# encoding=utf-8
import jieba

seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list))  # 全模式

seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list))  # 精确模式

seg_list = jieba.cut("他来到了网易杭研大厦")  # 默认是精确模式
print(", ".join(seg_list))

seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造")  # 搜索引擎模式
print(", ".join(seg_list))

  输出结果: 

【全模式】: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学
 
【精确模式】: 我/ 来到/ 北京/ 清华大学
 
【新词识别】:他, 来到, 了, 网易, 杭研, 大厦    (此处,“杭研”并没有在词典中,但是也被Viterbi算法识别出来了)
 
【搜索引擎模式】: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造

2.3利用词频做词云

利用词频去制作图,主要是把文本cut,然后统计词数。最好是绘制词频的直方图,更加直观明白,但是我就不写了贴上text的文本。这是参考别人写的代码,改的。主要是知道怎么样去设置词频云图。细节参考 词频云图

1、fit_words(frequencies) //根据词频生成词云【frequencies,为字典类型】
2、generate(text) //根据文本生成词云
3、generate_from_frequencies(frequencies[, ...]) //根据词频生成词云
4、generate_from_text(text) //根据文本生成词云
5、process_text(text) //将长文本分词并去除屏蔽词(此处指英语,中文分词还是需要自己用别的库先行实现,使用上面的 fit_words(frequencies) )
6、recolor([random_state, color_func, colormap]) //对现有输出重新着色。重新上色会比重新生成整个词云快很多。
7、to_array() //转化为 numpy array
8、to_file(filename) //输出到文件
import jieba
import codecs
from scipy.misc import imread
import os
from os import path
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
from wordcloud import WordCloud, ImageColorGenerator
from matplotlib.font_manager import *
import numpy as np





def read():
    '''
    获取文档对象,将文档内容按段落读入
    '''
    cut_text = open('E://pythonnotebook//text.txt', 'r').read()

    return cut_text

def segment(cut_text):
    '''
    用jieba分词对输入文档进行分词,并保存至本地(根据情况可跳过)
    '''
    cut_text = ' '.join(jieba.cut(cut_text, cut_all=False)) #seg_list为str类型

    #分词后存到cut_text1.text中
    text_after_segment = open('cut_text1.txt', 'w+')##分词后的文档
    text_after_segment.write(cut_text)
    text_after_segment.close()

    return cut_text

def wordCount(text):
    '''
        该函数实现词频的统计,并将统计结果存储至本地。
        在制作词云的过程中用不到,主要是在画词频统计图时用到。
    '''
    word_lst = []
    word_dict = {}
    with open('E://pythonnotebook//词频统计(去停用词).txt','w') as wf2: 
        word_lst.append(text.split(' ')) 
        for item in word_lst:
            for item2 in item:
                if item2 not in word_dict: 
                    word_dict[item2] = 1
                else:
                    word_dict[item2] += 1

        word_dict_sorted = dict(sorted(word_dict.items(), key = lambda item:item[1], reverse=True))#按照词频从大到小排序
        for key in word_dict_sorted:
            wf2.write(key+' '+str(word_dict_sorted[key])+'\n') 
    wf2.close()

    
def drawWordCloud(text):
    '''
        制作词云
        设置词云参数
    '''
    color_mask = imread('E://pythonnotebook//cloud2.jpg') # 读取背景图片,注意路径
    wc = WordCloud(  
        font_path = 'simfang.ttf',   
        background_color = 'white',  
        mask = color_mask,  
        max_words = 1000,  
        max_font_size = 100 
        #color_func=image_colors                                    
        )  
    wc.generate(text) # 产生词云
    
    wc.to_file("ciyun.jpg") #保存图片
    #  显示词云图片
    plt.imshow(wc, interpolation="bilinear")
    plt.axis('off')

    #这里主要为了实现词云图片按照图片颜色取色
    plt.figure()
    image_colors = ImageColorGenerator(color_mask)##产生图片的词云
    plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
    plt.axis("off")
    plt.show()
    
def removeStopWords(seg_list):
    '''
    自行下载stopwords1893.txt停用词表,该函数实现去停用词
    '''
    wordlist_stopwords_removed = []

    stop_words = open('E://pythonnotebook//stopwords1893.txt')
    stop_words_text = stop_words.read()

    stop_words.close()

    stop_words_text_list = stop_words_text.split('\n')
    after_seg_text_list = seg_list.split(' ')

    for word in after_seg_text_list:
        if word not in stop_words_text_list:
            wordlist_stopwords_removed.append(word)

    without_stopwords = open('E://pythonnotebook//分词结果(去停用词).txt', 'w')
    without_stopwords.write(' '.join(wordlist_stopwords_removed))
    return ' '.join(wordlist_stopwords_removed)   
 
    
if __name__ == "__main__":
    cut_text = read()##读文件
    segment_list = segment(cut_text)##分词
    segment_list_remove_stopwords = removeStopWords(segment_list)##移除停止符号
    drawWordCloud(segment_list_remove_stopwords)##制作云图

python爬虫【1】——词云解释_第1张图片

python爬虫【1】——词云解释_第2张图片

 

你可能感兴趣的:(python_爬虫)