stylecloud:轻松解决词云的蒙版和配色

    科技2023-11-08  84

    1. wordcloud生成的词云

    之前小哥在Python助力报考2020年成都市公务员!一文中,将「职位的专业需求」使用wordcloud绘制成了词云。

    在使用wordcloud绘制词云时一般我们需要先找到一张合适的蒙版图,比如小哥使用的是Python的logo。

    然后将「蒙版图」和「字符串」传入wordcloud中生成词云。在使用wordcloud生成词云时经常会面临以下两个问题:

    寻找蒙版图

    调整配色方案

    为了使生成词云更加方便快捷,国外大神在wordcloud的基础上开发了一个新的库,stylecloud。

    本期小哥就为大家讲解stylecloud的基本用法。

    2. stylecloud参数详解:

    text: 传入的字符串列表

    file_path: 字符串的文本/ CSV的文件路径

    gradient: 渐变方向 [「default:」 None]('horizontal')

    size:stylecloud的大小(调大可提高图片清晰度)

    icon_name: stylecloud形状的图标名称 [「default:」 fas fa-flag]

    palette: 调色板 [「default:」 cartocolors.qualitative.Bold_5]

    colors: 用作文本颜色的颜色 [「default:」 None]

    background_color: 背景色(名称或十六进制)[「default:」 white]

    max_font_size: stylecloud中的最大字体大小 [「default:」 200]

    max_words: 要包含在stylecloud中的最大单词数 [「default:」 2000]

    stopwords: 用于过滤掉常见的停用词 [「default:」 True]

    custom_stopwords: list定制停用词列表 [「default:」 STOPWORDS, via word_cloud]

    output_name: stylecloud的输出文件名 [「default:」 stylecloud.png]

    font_path: 要在stylecloud中使用的字体的.ttf文件的路径 [「default:」 uses included Staatliches font]

    random_state: 控制文字和颜色的随机状态 [「default:」 None]

    collocations: 是否包括两个单词的搭配(二字组)。与基本word_cloud软件包的行为相同 [「default:」 True]

    invert_mask: 是否反转图标掩码,因此单词填充除图标掩码以外的所有空格 [「default:」 False]

    stylecloud可支持传入字「符串列表」或「词汇文件」(txt或csv)。接下来小哥以处理好的「专业名称txt文件」进行操作。

    3. 一行代码生成词云

    import stylecloud from IPython.display import Image  stylecloud.gen_stylecloud(file_path='words.txt', collocations=False,                           font_path=r'‪C:\Windows\Fonts\msyh.ttc',                           size=800,                           output_name='词云.png') # 在jupyter中可视化词云 Image(filename='词云.png')

    4. icon_name:修改形状(fas fa-)

    在指定网站寻找需要的蒙版图,然后只需将蒙版图的名称写入(fas fa-名称)即可使用。

    更多免费形状链接:https://fontawesome.com/icons?d=gallery&m=free

    stylecloud.gen_stylecloud(file_path='words.txt', collocations=False,                           font_path=r'‪C:\Windows\Fonts\msyh.ttc',                           icon_name='fas fa-dove',size=800,                           output_name='词云2.png') Image(filename='词云2.png')

    5. palette:修改配色

    在指定网站寻找需要的配色,然后只需将配色方案的名称按一定格式写入即可使用。

    更多palette:https://jiffyclub.github.io/palettable/

    stylecloud.gen_stylecloud(file_path='words.txt', collocations=False,                           palette='cartocolors.qualitative.Pastel_5',                           font_path=r'‪C:\Windows\Fonts\msyh.ttc',                           icon_name='fas fa-cloud',size=800,                           output_name='词云3.png') Image(filename='词云3.png')

    Processed: 0.025, SQL: 8