python wordcloud模块

2024-09-06 03:32
文章标签 python 模块 wordcloud

本文主要是介绍python wordcloud模块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • 参考:https://amueller.github.io/word_cloud/auto_examples/colored.html#colored-py
    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)
参数:
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 //设置需要屏蔽的词,如果为空,则使用内置的STOPWORDSbackground_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_funcregexp : 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)   //输出到文件

from os import path
from scipy.misc import imread
import matplotlib.pyplot as pltfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator# 获取当前文件路径
# __file__ 为当前文件, 在ide中运行此行会报错,可改为
# d = path.dirname('.')
d = path.dirname(__file__)# 读取文本 alice.txt 在包文件的example目录下
#内容为
"""
Project Gutenberg's Alice's Adventures in Wonderland, by Lewis CarrollThis eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.org
"""
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 = imread(path.join(d, "alice_color.png"))wc = WordCloud(background_color="white", #背景颜色
max_words=2000,# 词云显示的最大词数
mask=alice_coloring,#设置背景图片
stopwords=STOPWORDS.add("said"),
max_font_size=40, #字体最大值
random_state=42)
# 生成词云, 可以用generate输入全部文本(中文不好分词),也可以我们计算好词频后使用generate_from_frequencies函数
wc.generate(text)
# wc.generate_from_frequencies(txt_freq)
# txt_freq例子为[('词a', 100),('词b', 90),('词c', 80)]
# 从背景图片生成颜色值
image_colors = ImageColorGenerator(alice_coloring)# 以下代码显示图片
plt.imshow(wc)
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))
plt.axis("off")
# 绘制背景图片为颜色的图片
plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
# 保存图片
wc.to_file(path.join(d, "名称.png"))

这里写图片描述
这里写图片描述

#!/usr/bin/env python
"""
Masked wordcloud
================Using a mask you can generate wordclouds in arbitrary shapes.
"""from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as pltfrom wordcloud import WordCloud, STOPWORDSd = path.dirname(__file__)# Read the whole text.
text = open(path.join(d, 'alice.txt')).read()# read the mask image
# taken from
# http://www.stencilry.org/stencils/movies/alice%20in%20wonderland/255fk.jpg
alice_mask = np.array(Image.open(path.join(d, "alice_mask.png")))stopwords = set(STOPWORDS)
stopwords.add("said")wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,stopwords=stopwords)
# generate word cloud
wc.generate(text)# store to file
wc.to_file(path.join(d, "alice.png"))# show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()
#coding:utf-8  
from os import path  
from scipy.misc import imread  
import matplotlib.pyplot as plt  
import jieba  from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator  stopwords = {}  
def importStopword(filename=''):  global stopwords  f = open(filename, 'r', encoding='utf-8')  line = f.readline().rstrip()  while line:  stopwords.setdefault(line, 0)  stopwords[line] = 1  line = f.readline().rstrip()  f.close()  def processChinese(text):  seg_generator = jieba.cut(text)  # 使用结巴分词,也可以不使用  seg_list = [i for i in seg_generator if i not in stopwords]  seg_list = [i for i in seg_list if i != u' ']  seg_list = r' '.join(seg_list)  return seg_list  importStopword(filename='./stopwords.txt')  # 获取当前文件路径  
# __file__ 为当前文件, 在ide中运行此行会报错,可改为  
# d = path.dirname('.')  
d = path.dirname(__file__)  text = open(path.join(d, 'love.txt'),encoding ='utf-8').read()  #如果是中文  
#text = processChinese(text)#中文不好分词,使用Jieba分词进行  # read the mask / color image  
# taken from http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010  
# 设置背景图片  
back_coloring = imread(path.join(d, "./image/love.jpg"))  wc = WordCloud( font_path='./font/cabin-sketch.bold.ttf',#设置字体  background_color="black", #背景颜色  max_words=2000,# 词云显示的最大词数  mask=back_coloring,#设置背景图片  max_font_size=100, #字体最大值  random_state=42,  )  
# 生成词云, 可以用generate输入全部文本(中文不好分词),也可以我们计算好词频后使用generate_from_frequencies函数  
wc.generate(text)  
# wc.generate_from_frequencies(txt_freq)  
# txt_freq例子为[('词a', 100),('词b', 90),('词c', 80)]  
# 从背景图片生成颜色值  
image_colors = ImageColorGenerator(back_coloring)  plt.figure()  
# 以下代码显示图片  
plt.imshow(wc)  
plt.axis("off")  
plt.show()  
# 绘制词云  # 保存图片  
wc.to_file(path.join(d, "名称.png"))  

这篇关于python wordcloud模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1140873

相关文章

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Python版本与package版本兼容性检查方法总结

《Python版本与package版本兼容性检查方法总结》:本文主要介绍Python版本与package版本兼容性检查方法的相关资料,文中提供四种检查方法,分别是pip查询、conda管理、PyP... 目录引言为什么会出现兼容性问题方法一:用 pip 官方命令查询可用版本方法二:conda 管理包环境方法

基于Python开发Windows自动更新控制工具

《基于Python开发Windows自动更新控制工具》在当今数字化时代,操作系统更新已成为计算机维护的重要组成部分,本文介绍一款基于Python和PyQt5的Windows自动更新控制工具,有需要的可... 目录设计原理与技术实现系统架构概述数学建模工具界面完整代码实现技术深度分析多层级控制理论服务层控制注

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

Python打包成exe常用的四种方法小结

《Python打包成exe常用的四种方法小结》本文主要介绍了Python打包成exe常用的四种方法,包括PyInstaller、cx_Freeze、Py2exe、Nuitka,文中通过示例代码介绍的非... 目录一.PyInstaller11.安装:2. PyInstaller常用参数下面是pyinstal

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数