zoukankan      html  css  js  c++  java
  • 词云

    词云是根据词频生成的,字体越大代表词频越高;

    词云只是词频的可视化,意义跟词频一样;

    python 使用 wordcloud 模块 生成词云,主要分两步:

    1. 创建 WordCloud 对象

    2. 直接根据文本 或者 根据词频 生成词云

    创建 wc 对象

    wordcloud 参数介绍

    font_path : string  #字体路径,如:font_path = '黑体.ttf'
    width : int (default=400) #输出的图像宽度,默认为400像素
    height : int (default=200) #输出的图像高度,默认为200像素
    prefer_horizontal : float (default=0.90) #词语水平方向排版出现的频率,默认 0.9 (所以词语垂直方向排版出现频率为 0.1 )
    mask : nd-array or None (default=None) #背景布,除去纯白部分都会用来填充词云
    scale : float (default=1) #按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍
    min_font_size : int (default=4) #显示的最小的字体大小
    max_font_size : int or None (default=None) #显示的最大的字体大小
    font_step : int (default=1) #字体步长,如果步长大于1,会加快运算但是可能导致结果出现较大的误差
    max_words : number (default=200) #要显示的词的最大个数
    stopwords : set of strings or None #设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS。很多文章都没有说清楚要怎么写屏蔽词,其实就是一个list。
    background_color : color value (default=”black”) #背景颜色,如background_color='white',背景颜色为白色
    mode : string (default=”RGB”) #当参数为“RGBA”并且background_color不为空时,背景为透明
    relative_scaling : float (default=.5) #词频和字体大小的关联性
    color_func : callable, default=None #生成新颜色的函数,如果为空,则使用 self.color_func
    regexp : string or None (optional) #使用正则表达式分隔输入的文本
    collocations : bool, default=True #是否包括两个词的搭配
    colormap : string or matplotlib colormap, default=”viridis” #给每个单词随机分配颜色,若指定color_func,则忽略该方法
    random_state : int or None  #为每个单词返回一个PIL颜色

    根据文本或者词频生成词云

    from wordcloud import WordCloud
    from collections import Counter
    
    
    text = '''Fame,wealth and knowledge are merely worldly possessions that are within the reach of anybody sriving for them.
    But your experience of and feelings about life are your own and not be shared.No one can live your life over again 
    after your death.A full awareness of thins will povnt out to you that the most important thing in your existence is 
    your distinctive individuality or something special of yours.What really counts is not your worldly success but your 
    peculiar insight into the meaning of life and your commintment to it,which add luster to your personality.'''
    
    wc = WordCloud(font_path='simkai.ttf',
                   background_color='black',
                   max_words=100)
    
    
    ##### 直接根据文本生成词云
    ## method1
    word_tf = wc.generate(text)     # 返回一个迭代器
    print(dir(word_tf))
    # ['background_color', 'collocation_threshold', 'collocations', 'color_func', 'colormap', 'contour_color',
    #  'contour_width', 'fit_words', 'font_path', 'font_step', 'generate', 'generate_from_frequencies',
    #  'generate_from_text', 'height', 'include_numbers', 'layout_', 'margin', 'mask', 'max_font_size',
    #  'max_words', 'min_font_size', 'min_word_length', 'mode', 'normalize_plurals', 'prefer_horizontal',
    #  'process_text', 'random_state', 'recolor', 'regexp', 'relative_scaling', 'repeat', 'scale', 'stopwords',
    #  'to_array', 'to_file', 'to_html', 'to_image', 'to_svg', 'width', 'words_']
    
    wc.to_file('t1.png')    # 或者 word_tf.to_file('t1.png')
    img = word_tf.to_image()
    img.show()
    
    ## method2
    word_tf = wc.generate_from_text(text)
    word_tf.to_file('t2.png')
    img = word_tf.to_image()
    img.show()
    
    
    ##### 根据词频生成词云
    text = text.split(' ')
    word_tf = Counter(text)
    
    ## method1
    wc.generate_from_frequencies(word_tf)
    wc.to_file('t3.png')
    img = wc.to_image()
    img.show()
    
    ## method2
    wc.fit_words(word_tf)
    wc.to_file('t4.png')
    img = wc.to_image()
    img.show()
    
    
    ##### 其他操作见 dir(wc)

    完整示例

    # coding:utf-8
    import jieba  # 分词
    import matplotlib.pyplot as plt  # 数据可视化
    from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS  # 词云
    import numpy as np  # 科学计算
    from PIL import Image  # 处理图片
    
    
    def draw_cloud(text, graph, save_name):
        textfile = open(text).read()  # 读取文本内容
        wordlist = jieba.cut(textfile, cut_all=False)  # 中文分词
        space_list = " ".join(wordlist)  # 连接词语
        backgroud = np.array(Image.open(graph))  # 背景轮廓图
        mywordcloud = WordCloud(background_color="white",  # 背景颜色
                                mask=backgroud,  # 写字用的背景图,从背景图取颜色
                                max_words=100,  # 最大词语数量
                                stopwords=STOPWORDS,  # 停用词
                                font_path="simkai.ttf",  # 字体
                                max_font_size=200,  # 最大字体尺寸
                                random_state=50,  # 随机角度
                                scale=2,
                                collocations=False,  # 避免重复单词
                                )
        mywordcloud = mywordcloud.generate(space_list)  # 生成词云
        ImageColorGenerator(backgroud)  # 生成词云的颜色
        plt.imsave(save_name, mywordcloud)  # 保存图片
        plt.imshow(mywordcloud)  # 显示词云
        plt.axis("off")  # 关闭保存
        plt.show()
    
    
    if __name__ == '__main__':
        draw_cloud(text="government.txt", graph="china_map.jpg", save_name='2019政府工作报告词云.png')

    更多方法有空再更新

    OSError: cannot open resource解决方案

    解决方法见 参考资料,这里只补充一下 中文处理方式;

    找到 控制面板 --- 字体 - 中文字体 - 属性,把属性值 粘到 wc 对象 的 font_path 处即可 

    wc = WordCloud(
            background_color = 'white', # 背景颜色
            font_path = 'STFANGSO.TTF'  # 字体样式
        )

    参考资料:

    https://blog.csdn.net/qq_39985298/article/details/90234830  wordcloud参数说明,带示例

    https://www.jb51.net/article/169633.htm  Python制作词云图代码实例

    https://www.cnblogs.com/liangmingshen/p/11312257.html  已知词频生成词云图(数据库到生成词云)--generate_from_frequencies(WordCloud),带示例

    https://blog.csdn.net/qq_43448491/article/details/87875600  关于调用wordcloud库时报错OSError: cannot open resource解决方案,中文处理方法

  • 相关阅读:
    一点技巧
    题解G
    WA七次,疯了》》》》》OTZ
    就是过不了啊无奈。。。。。水题都过不了…………OTZ OTZ OTZ
    [IOS]使用UIScrollView和UIPageControl显示半透明帮助蒙板
    [System]几种同步方式
    [Objective C] Singleton类的一个模版
    [IOS] 自定义AlertView实现模态对话框
    [IOS] UIKit Animation
    [IOS]使用genstrings和NSLocalizedString实现App文本的本地化
  • 原文地址:https://www.cnblogs.com/yanshw/p/15049194.html
Copyright © 2011-2022 走看看