整体简介

基于Python的词云生成类库,很好用,而且功能强大.博主个人比较推荐
github:https://github.com/amueller/word_cloud
官方地址:https://amueller.github.io/word_cloud/
写这篇文章花费一个半小时,阅读需要十五分钟,读完本篇文章后您将能上手wordcloud

中文词云与其他要点,我将会在下一篇文章中介绍

快速生成词云

from wordcloud import WordCloudf = open(u'txt/AliceEN.txt','r').read()
wordcloud = WordCloud(background_color="white",width=1000, height=860, margin=2).generate(f)# width,height,margin可以设置图片属性# generate 可以对全部文本进行自动分词,但是他对中文支持不好,对中文的分词处理请看我的下一篇文章
#wordcloud = WordCloud(font_path = r'D:\Fonts\simkai.ttf').generate(f)
# 你可以通过font_path参数来设置字体集#background_color参数为设置背景颜色,默认颜色为黑色import matplotlib.pyplot as plt
plt.imshow(wordcloud)
plt.axis("off")
plt.show()wordcloud.to_file('test.png')
# 保存图片,但是在第三模块的例子中 图片大小将会按照 mask 保存

自定义字体颜色

这段代码主要来自wordcloud的github,你可以在github下载该例子

#!/usr/bin/env python
"""
Colored by Group Example
========================Generating a word cloud that assigns colors to words based on
a predefined mapping from colors to words
"""from wordcloud import (WordCloud, get_single_color_func)
import matplotlib.pyplot as pltclass SimpleGroupedColorFunc(object):"""Create a color function object which assigns EXACT colorsto certain words based on the color to words mappingParameters----------color_to_words : dict(str -> list(str))A dictionary that maps a color to the list of words.default_color : strColor that will be assigned to a word that's not a memberof any value from color_to_words."""def __init__(self, color_to_words, default_color):self.word_to_color = {word: colorfor (color, words) in color_to_words.items()for word in words}self.default_color = default_colordef __call__(self, word, **kwargs):return self.word_to_color.get(word, self.default_color)class GroupedColorFunc(object):"""Create a color function object which assigns DIFFERENT SHADES ofspecified colors to certain words based on the color to words mapping.Uses wordcloud.get_single_color_funcParameters----------color_to_words : dict(str -> list(str))A dictionary that maps a color to the list of words.default_color : strColor that will be assigned to a word that's not a memberof any value from color_to_words."""def __init__(self, color_to_words, default_color):self.color_func_to_words = [(get_single_color_func(color), set(words))for (color, words) in color_to_words.items()]self.default_color_func = get_single_color_func(default_color)def get_color_func(self, word):"""Returns a single_color_func associated with the word"""try:color_func = next(color_func for (color_func, words) in self.color_func_to_wordsif word in words)except StopIteration:color_func = self.default_color_funcreturn color_funcdef __call__(self, word, **kwargs):return self.get_color_func(word)(word, **kwargs)text = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""# Since the text is small collocations are turned off and text is lower-cased
wc = WordCloud(collocations=False).generate(text.lower())# 自定义所有单词的颜色
color_to_words = {# words below will be colored with a green single color function'#00ff00': ['beautiful', 'explicit', 'simple', 'sparse','readability', 'rules', 'practicality','explicitly', 'one', 'now', 'easy', 'obvious', 'better'],# will be colored with a red single color function'red': ['ugly', 'implicit', 'complex', 'complicated', 'nested','dense', 'special', 'errors', 'silently', 'ambiguity','guess', 'hard']
}# Words that are not in any of the color_to_words values
# will be colored with a grey single color function
default_color = 'grey'# Create a color function with single tone
# grouped_color_func = SimpleGroupedColorFunc(color_to_words, default_color)# Create a color function with multiple tones
grouped_color_func = GroupedColorFunc(color_to_words, default_color)# Apply our color function
# 如果你也可以将color_func的参数设置为图片,详细的说明请看 下一部分
wc.recolor(color_func=grouped_color_func)# Plot
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

利用背景图片生成词云,设置停用词词集

该段代码主要来自于wordcloud的github,你同样可以在github下载该例子以及原图片与效果图

#!/usr/bin/env python
"""
Image-colored wordcloud
=======================You can color a word-cloud by using an image-based coloring strategy
implemented in ImageColorGenerator. It uses the average color of the region
occupied by the word in a source image. You can combine this with masking -
pure-white will be interpreted as 'don't occupy' by the WordCloud object when
passed as mask.
If you want white as a legal color, you can just pass a different image to
"mask", but make sure the image shapes line up.
"""from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as pltfrom wordcloud import WordCloud, STOPWORDS, ImageColorGeneratord = path.dirname(__file__)# Read the whole text.
text = open(path.join(d, 'alice.txt')).read()# read the mask / color image taken from
# http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010
alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))# 设置停用词
stopwords = set(STOPWORDS)
stopwords.add("said")# 你可以通过 mask 参数 来设置词云形状
wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,stopwords=stopwords, max_font_size=40, random_state=42)
# generate word cloud
wc.generate(text)# create coloring from image
image_colors = ImageColorGenerator(alice_coloring)# show
# 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.figure()
# recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
# 我们还可以直接在构造函数中直接给颜色
# 通过这种方式词云将会按照给定的图片颜色布局生成字体颜色策略
plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
plt.axis("off")
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")
plt.axis("off")
plt.show()

展示效果如下:

Python词云 wordcloud 十五分钟入门与进阶相关推荐

  1. Python中文分词 jieba 十五分钟入门与进阶

    文章目录 整体介绍 三种分词模式与一个参数 关键词提取 中文歧义测试与去除停用词 三种可以让分词更准确的方法 并行计算 整体介绍 jieba 基于Python的中文分词工具,安装使用非常方便,直接pi ...

  2. 数据美化 | 更清晰的Python词云wordcloud

    看了前面的词云教程,你可能会有一个疑问.为什么前面生成的词云图片不清晰呢?现在我们就来解决这个问题. 词云的属性 即WordCloud对象的属性: from wordcloud import Word ...

  3. python词云 wordcloud+jieba生成中文词云图

    简介 Python+jieba+wordcloud+txt+gif生成动态中文词云 本文基于爬虫爬取某微信号三个月的文章为例,展示了生成中文词云的完整过程.本文需要的两个核心Python类库: jie ...

  4. python词云 wordcloud库详细使用教程

    文章目录 前言 使用wordcloud生成词云的步骤 API参考 实例 从一段文本建立词云 根据蒙版建立词云 从词频建立词云 从图片颜色建立词云 传入中文字体路径解决乱码问题 前言 "词云& ...

  5. python词云乱码_python词云库wordCloud使用方法详解(解决中文乱码)

    文章中的例子主要借鉴wordColud的examples,在文章对examples中的例子做了一些改动. 一.wordColud设计中文词云乱码 使用wordColud设计词云的时候可能会产生乱码问题 ...

  6. python词云库wordcloud自定义词云制作步骤详解

    读书使人充实,讨论使人机智,笔记使人准确-.凡有所学,皆成性格. ---- (英国)培根 文章目录 wordcloud库常规方法 第三方库 读取文件 自定义绘制指定形状的词云 wordcloud库常规 ...

  7. python词云形状为六边形怎么做_python第三方库wordcloud绘制任意形状词云教程

    版权声明:转载附链接哦.https://blog.csdn.net/weixin_43886356/article/details/86711292 此篇教程划分为两种情况,原文本为汉字和原文本为英文 ...

  8. python词云安装什么库_python词云安装什么库

    python词云需要安装wordcloud库. 安装方法: 在cmd使用pip install wordcloud命令即可安装. wordcloud库把词云当作一个WordCloud对象:wordcl ...

  9. python词云_python词云

    python词云[编辑] 概述 python词云是一种构建词云的方法,利用通用的编程语言Python来做词云,虽然不如专用工具便捷,但是适用范围很广,满足了不同人对词云的个性化需求. 一.Python ...

最新文章

  1. android adb命令,向开发手机添加文件
  2. 计算机软件和程序设计基本知识,计算机语言与程序设计
  3. 关于外挂新手最常见的30个问题
  4. 纳税服务系统十一【抽取BaseService、条件查询】
  5. CSS分别设置Input样式(按input类型)
  6. javaweb学习总结(十)——HttpServletRequest对象(一)(转)
  7. hdu 3590——PP and QQ
  8. redis rua解决库存问题_如何解决高并发下的库存安全问题,没你想得那么复杂(附源码)...
  9. c语言静态变量存在堆还是栈,c 类 static 函数 什么样是静态变量?嵌入式C语言的堆栈管理如何实现...
  10. linux pandas教程_这7种Python的全新玩法,你们一定不知道!(附赠Python教程)
  11. 【万里征程——Windows App开发】DatePickerTimepicker
  12. 解决CentOS无法解析域名的问题
  13. asp.net dev xtraReporting(一)静态页面
  14. 郑州大学远程教育学院C语言程序设计题库(一)
  15. SUI Mobile 手机移动端H5框架
  16. 曾国藩修身十三条,值得学习
  17. 安装移动视频监控 即时监控地铁车厢
  18. 四则运算之结对作业报告
  19. 每天重启mycat的好处_路由器需要每天都关吗?其实很多人都弄错了
  20. centos7 firewall-cmd 命令报错 ModuleNotFoundError: No module named 'gi'

热门文章

  1. 你所不知道的ASP.NET Core MVC/WebApi基础系列(二)
  2. CIO时代客户交流会,强强联合共筑电子政务美好未来
  3. QQ空间Python爬虫v2.0--点赞数据分析
  4. 希捷推2TB 2.5英寸SSHD和5TB 2.5英寸机械硬盘
  5. Endpoint 理解
  6. 常见.Net 英文专业词汇收集
  7. 基于Leaflet和高德Web API扩展地理编码服务
  8. “数据中台”万字深度思考
  9. 为什么 wait 方法要在 synchronized 中调用?
  10. Spring Boot 到底是怎么做到自动配置的?