美文网首页
Python3 生成英文词云

Python3 生成英文词云

作者: tafanfly | 来源:发表于2019-08-27 16:58 被阅读0次

    词云

    经常看到词云图片,好奇怎么制作的,在此分享下过程。
    词云必备工具是wordcloud库,文档如下:


    wordcloud基本用法

    wordcloud功能强大且使用简单,只需要导入库即可, 命令from wordcloud import WordCloud
    下面是wordcloud的函数和参数具体介绍,后面会举例如何使用。

    class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9, mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None, background_color='black', max_font_size=None, font_step=1, mode='RGB', relative_scaling='auto', regexp=None, collocations=True, colormap=None, normalize_plurals=True, contour_width=0, contour_color='black', repeat=False, include_numbers=False, min_word_length=0)
    
    
    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) | 如果参数为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代。除全白(#FFFFFF)的部分将不会绘制,其余部分会用于绘制词云。如:bg_pic = imread('读取一张图片.png'),背景图片的画布一定要设置为白色(#FFFFFF),然后显示的形状为不是白色的其他颜色。可以用ps工具将自己要显示的形状复制到一个纯白色的画布上再保存,就ok了。
    
    contour_width: float (default=0) | 如果遮罩不为空并且contour_width 大于0, 绘制遮罩轮廓
    
    contour_color: color value (default=”black”) | 遮罩轮廓颜色
    
    scale : float (default=1) | 按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍。
    
    min_font_size : int (default=4) | 显示的最小的字体大小
    
    font_step : int (default=1) | 字体步长,如果步长大于1,会加快运算但是可能导致结果出现较大的误差。
    
    max_words : number (default=200) | 要显示的词的最大个数
    
    stopwords : set of strings or None | 设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS
    
    background_color : color value (default=”black”) | 背景颜色,如background_color='white',背景颜色为白色。
    
    max_font_size : int or None (default=None) | 显示的最大的字体大小
    
    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,则忽略该方法。
    
    
    fit_words(frequencies)  | 根据词频生成词云
    generate(text)  | 根据文本生成词云
    generate_from_frequencies(frequencies[, ...])   | 根据词频生成词云
    generate_from_text(text)    | 根据文本生成词云
    process_text(text)  | 将长文本分词并去除屏蔽词(此处指英语,中文分词还是需要自己用别的库先行实现,使用上面的 fit_words(frequencies) )
    recolor([random_state, color_func, colormap])   | 对现有输出重新着色。重新上色会比重新生成整个词云快很多。
    to_array()  | 转化为 numpy array
    to_file(filename)   | 输出到文件
    
    

    简单生成词云

    alice.txt 的内容是https://github.com/amueller/word_cloud/blob/master/examples/alice.txt

    #!/usr/bin/env python
    # coding=utf-8
    
    
    import os
    from wordcloud import WordCloud
    
    
    CURDIR = os.path.abspath(os.path.dirname(__file__))
    TEXT = os.path.join(CURDIR,  'alice.txt')
    
    
    def read_the_words(text=TEXT):
        with open(text, 'r') as rp:
            content = rp.read()
        return content
    
    def create_worlds_cloud():
        words = read_the_words()
        wc = WordCloud(max_font_size=40)
        wc.generate(words)
        wc.to_file('new.png')
    
    if __name__ == '__main__':
        create_worlds_cloud()
    

    生成的图片,是默认的矩形状态


    new.png

    进阶版词云

    #!/usr/bin/env python
    # coding=utf-8
    
    
    import os
    import numpy as np
    from PIL import Image
    from wordcloud import WordCloud, STOPWORDS
    
    
    CURDIR = os.path.abspath(os.path.dirname(__file__))
    TEXT = os.path.join(CURDIR,  'alice.txt')
    PICTURE= os.path.join(CURDIR,  'alice.png')
    
    
    def read_the_words(text=TEXT):
        with open(text, 'r') as rp:
            content = rp.read()
        return content
    
    def create_worlds_cloud():
        background = np.array(Image.open(PICTURE))
        stopwords = set(STOPWORDS)
        stopwords.add("said")
        words = read_the_words()
        wc = WordCloud(background_color="white",
                       mask=background,
                       stopwords=stopwords)
        wc.generate(words)
        wc.to_file('girl.png')
    
    if __name__ == '__main__':
        create_worlds_cloud()
    
    girl.png

    应用&参考

    更多应用见官网: https://github.com/amueller/word_cloud/tree/master/examples

    相关文章

      网友评论

          本文标题:Python3 生成英文词云

          本文链接:https://www.haomeiwen.com/subject/pmleectx.html