Python 制作词云的WordCloud参数用法说明

场景

官方API:

https://amueller.github.io/word_cloud/generated/wordcloud.WordCloud.html

实现

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了。
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,则忽略该方法
random_state : int or None #为每个单词返回一个PIL颜色
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) #输出到文件

补充:生成词云之python中WordCloud包的用法

效果图:

这是python中使用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=0.5, regexp=None, collocations=True,colormap=None, normalize_plurals=True)

这是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) //如果参数为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代。除全白(#FFFFFF)的部分将不会绘制,其余部分会用于绘制词云。如:bg_pic = imread('读取一张图片.png'),背景图片的画布一定要设置为白色(#FFFFFF),然后显示的形状为不是白色的其他颜色。可以用ps工具将自己要显示的形状复制到一个纯白色的画布上再保存,就ok了。
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) //输出到文件

例子:

想要生成的词云的形状:

图中黑色部分就是词云的将要显示的部分,白色部分不显示任何词。

下面是一个文本文档:

How the Word Cloud Generator Works

The layout algorithm for positioning words without overlap is available on GitHub under an open source license as d3-cloud. Note that this is the only the layout algorithm and any code for converting text into words and rendering the final output requires additional development.

As word placement can be quite slow for more than a few hundred words, the layout algorithm can be run asynchronously, with a configurable time step size. This makes it possible to animate words as they are placed without stuttering. It is recommended to always use a time step even without animations as it prevents the browser's event loop from blocking while placing the words.

The layout algorithm itself is incredibly simple. For each word, starting with the most “important”:

Attempt to place the word at some starting point: usually near the middle, or somewhere on a central horizontal line. If the word intersects with any previously placed words, move it one step along an increasing spiral. Repeat until no intersections are found. The hard part is making it perform efficiently! According to Jonathan Feinberg, Wordle uses a combination of hierarchical bounding boxes and quadtrees to achieve reasonable speeds.

Glyphs in JavaScript

There isn't a way to retrieve precise glyph shapes via the DOM, except perhaps for SVG fonts. Instead, we draw each word to a hidden canvas element, and retrieve the pixel data.

Retrieving the pixel data separately for each word is expensive, so we draw as many words as possible and then retrieve their pixels in a batch operation.

Sprites and Masks

My initial implementation performed collision detection using sprite masks. Once a word is placed, it doesn't move, so we can copy it to the appropriate position in a larger sprite representing the whole placement area.

The advantage of this is that collision detection only involves comparing a candidate sprite with the relevant area of this larger sprite, rather than comparing with each previous word separately.

Somewhat surprisingly, a simple low-level hack made a tremendous difference: when constructing the sprite I compressed blocks of 32 1-bit pixels into 32-bit integers, thus reducing the number of checks (and memory) by 32 times.

In fact, this turned out to beat my hierarchical bounding box with quadtree implementation on everything I tried it on (even very large areas and font sizes). I think this is primarily because the sprite version only needs to perform a single collision test per candidate area, whereas the bounding box version has to compare with every other previously placed word that overlaps slightly with the candidate area.

Another possibility would be to merge a word's tree with a single large tree once it is placed. I think this operation would be fairly expensive though compared with the analagous sprite mask operation, which is essentially ORing a whole block.

从这个文本中生成一个词云,代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#coding=utf-8
#导入wordcloud模块和matplotlib模块
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from scipy.misc import imread
#读取一个txt文件
text = open('test.txt','r').read()
#读入背景图片
bg_pic = imread('3.png')
#生成词云
wordcloud = WordCloud(mask=bg_pic,background_color='white',scale=1.5).generate(text)
image_colors = ImageColorGenerator(bg_pic)
#显示词云图片
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
#保存图片
wordcloud.to_file('test.jpg')

运行结果:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

(0)

相关推荐

  • Python中的wordcloud库安装问题及解决方法

    今天下载wordcloud的时候出现了很多问题,在此总结总结 1.问题一:You are using pip version 19.0.3, however version 20.0.2 is available-问题 解决方法: 打开cmd输入如下命令 python -m pip install -U pip 2.问题二:error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual 解决方法: 方法1(不

  • Python基于jieba, wordcloud库生成中文词云

    代码如下 import wordcloud import jieba font = r'C:\Windows\Fonts\simfang.ttf' w = wordcloud.WordCloud(height = 700, width = 1000, font_path=font, \ stopwords=['et','al', 'Crampin', 'and','the', 'Liu'], max_words=30) with open('NSFC.txt', 'r') as f: txt =

  • Python基于wordcloud及jieba实现中国地图词云图

    热词图很酷炫,也非常适合热点事件,抓住重点,以图文结合的方式表现出来,很有冲击力.下面这段代码是制作热词图的,用到了以下技术: jieba,把文本分词 wordcloud,制作热图 chardet,辨别文件的编码格式,其中中文统一为GB18030,更加的兼容 imageio,提取图片的形状 其他:自动识别文件编码,自动识别txt文件,图片文件名与txt文件一致,使用的是四大名著的文本(自行百度),部分中国地图 上代码: import os import jieba import wordclou

  • Python WordCloud 修改色调的实现方式

    在绘制词云图时发现有的字颜色为黄色导致看不清因此需要修改整个词云图的色调为冷色调 具体的来说 wordcloud中的color_func 参数使得我们能够自定义颜色函数 def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None): h = randint(120,250) s = int(100.0 * 255.0 / 25

  • Python wordcloud库安装方法总结

    碰到有关于"词云"的概念,那就一定要用到本章教学库--wordcloud,这是第三方的库,主要是用于词云的展示,基本的单位也是以词云为主,利用它的功能,我们可以实现过滤文本信息,这样,就可以直观的观察到我们所需要的信息内容,因此,根据技能上的应用,在实际操作中还是非常常见的,下面来看下安装操作. 安装命令: pip install wordcloud 导入包: from wordcloud import WordCloud 常见方法: 1.加载文本及输出 w = wordcloud.W

  • 关于python3.9安装wordcloud出错的问题及解决办法

    本文给大家分享python3.9安装wordcloud出错解决经历,感兴趣的朋友一起看看吧 晚上闲的无聊,就想安装个词云玩玩,但是安装失败,出现命令在退出时发生错误,在网上找了很多的解决办法,但是一一不管用,试了在pycharm->settings->project interrupt 进行安装,不料还是报错, 我开始是用pip install --upgradepip 和pip install --upgrade setuptools来升级我的pip,但是没有什么用,还是一如既往的报错. 此

  • Python 制作词云的WordCloud参数用法说明

    场景 官方API: https://amueller.github.io/word_cloud/generated/wordcloud.WordCloud.html 实现 font_path : string #字体路径,需要展现什么字体就把该字体路径+后缀名写上,如:font_path = '黑体.ttf' width : int (default=400) #输出的画布宽度,默认为400像素 height : int (default=200) #输出的画布高度,默认为200像素 prefe

  • 用python制作词云视频详解

    使用到的第三方库 Package Version --------------- --------- baidu-aip 2.2.18.0 jieba 0.42.1 moviepy 1.0.3 numpy 1.20.2 opencv-python 4.5.1.48 Pillow 8.2.0 requests 2.25.1 wordcloud 1.8.1 you-get 0.4.1520 B站弹幕爬取 思路 通过视频BV号请求cid,再使用cid请求弹幕文件,最后使用正则表达式去匹配弹幕文本,将匹

  • 利用python 制作词云特效详情

    目录 一.特效预览 二.程序原理 三.程序源码 什么是 ​词云​ ​词云​ 其实就是就是对网络文本中出现频率较高的〝关键词〞予以视觉上的突出,形成〝关键词云层〞或〝关键词渲染〞从而过滤掉大量的文本信息 ​词云​ 也是数据可视化的一种形式.给出一段文本,根据关键词的出现频率而生成的一幅图像,人们只要扫一眼就能够明白其文章主旨. 一.特效预览 词云图: 二.程序原理 从给出的文本中,进行分词处理,然后将每个词出现的的频率进行统计 从给出的背景图片上,读出图片信息 将文本按照出现的频率进行画图,出现频

  • Python制作词云的方法

    需求: 看到朋友圈有人发词云照片,感觉自己也可以玩一玩,于是乎借助wordcloud实现功能. 环境: MacOS 10.12 +Python 2.7 +Wordcloud Windows通用 准备: 安装wordcloud $ pip install wordcloud SIP功能是Apple在OSX上推出的系统完整性保护功能,新版本的macOS直接用pip安装报错,在不关闭SIP功能的前提下,可以使用 $ pip install wordcloud --user -U 某些情况还会提示错误,

  • python爬取热搜制作词云

    环境:win10,64位,mysql5.7数据库,python3.9.7,ancod 逻辑流程: 1.首先爬取百度热搜,至少间隔1小时 2.存入文件,避免重复请求,如果本1小时有了不再请求 3.存入数据库,供词云包使用 1.爬取热搜,首先拿到url,使用的包urllib,有教程说urllib2是python2的. '''读取页面''' def readhtml(self,catchUrl): catchUrl=self.catchUrl if not catchUrl else catchUrl

  • python爬取豆瓣评论制作词云代码

    目录 一.爬取豆瓣热评 二.制作词云 总结 一.爬取豆瓣热评 该程序进行爬取豆瓣热评,将爬取的评论(json文件)保存到与该python文件同一级目录下注意需要下载这几个库:requests.lxml.json.time import requests from lxml import etree import json import time class Spider(object): def __init__(self): #seif.ure='https://movie.douban.co

  • Python制作词云图代码实例

    词云图是将词汇按照频率的高低显示不同大小而形成的图,可以一目了然地看出关键词.下面是词云图的python代码- #导入需要模块 import jieba import numpy as np import matplotlib.pyplot as plt from PIL import Image from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator text_road=str(input('请输入文章的路径:')) pi

  • Python基于WordCloud制作词云图

    这篇文章主要介绍了python基于WordCloud制作词云图,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1. 导入需要的包package import matplotlib.pyplot as plt from scipy.misc import imread from wordcloud import WordCloud,STOPWORDS import xlrd 2. 设置生成词云图的背景图片,最好是分辨率高且色彩边界分明的图片 de

  • python词云库wordcloud的使用方法与实例详解

    wordcloud是优秀的词云展示第三方库 一.基本使用 import jieba import wordcloud txt = open("1.txt", "r", encoding='utf-8').read() words = jieba.lcut(txt) txt_1 = " ".join(words) # print(txt1) w = wordcloud.WordCloud(font_path="msyh.ttc"

  • python如何用pyecharts制作词云图

    需要安装pyecharts pip install pyecharts -U 创建[demo6.py]并输入以下编码: from pyecharts import options as opts from pyecharts.charts import Page, WordCloud words = [ ("神医", 10000), ("马良", 6181), ("玛丽", 4386), ("终结者", 4055), (&qu

随机推荐