1、入门案例
"""
Minimal Example
===============
使用默认参数根据美国宪法生成方形的词云
"""
from os import path
from wordcloud import WordCloud
# matplotlib的方式展示生成的词云图像
import matplotlib.pyplot as plt
d = path.dirname(__file__)
# 读取整个文本
text = open(path.join(d, 'a.txt'), encoding="utf-8").read()
# 背景图片
# backgroud_Image = plt.imread('1.jpg')
# 生成一个词云图像
wordcloud = WordCloud( #background_color = 'white', # 设置背景颜色
# mask = backgroud_Image, # 设置背景图片
# max_words = 2000, # 设置最大现实的字数
# stopwords = STOPWORDS, # 设置停用词
font_path = 'C:/Windows/Fonts/simsun.ttc',# 设置字体格式,如不设置显示不了中文
# max_font_size = 50, # 设置字体最大值
# random_state = 30, # 设置有多少种随机生成状态,即有多少种配色方案
# width,height,margin 可以设置图片属性
# width=1000,
# height=600
)
wordcloud.generate(text)
# plt.imshow(wordcloud, interpolation='bilinear')
# plt.axis("off")
# max_font_size设定生成词云中的文字最大大小
# width,height,margin可以设置图片属性
# plt.figure() # 设置图片大小等
# plt.imshow(wordcloud, interpolation="bilinear")
# plt.axis("off")
# plt.show()
# pil方式展示生成的词云图像(如果你没有matplotlib)
image = wordcloud.to_image()
image.show()
2、使用蒙版图像可以生成任意形状的wordcloud
"""
Masked wordcloud
================
使用蒙版图像可以生成任意形状的wordcloud。
"""
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
d = path.dirname(__file__)
# 读取整个文本.
text = open(path.join(d, 'a.txt'),encoding="utf-8").read()
alice_mask = np.array(Image.open(path.join(d, "2.png")))
stopwords = set(STOPWORDS)
stopwords.add("said")
#设置词云的一些属性
wc = WordCloud(background_color="white", max_words=2000, mask=alice_mask,
font_path = 'C:/Windows/Fonts/simsun.ttc',# 设置字体格式,如不设置显示不了中文
stopwords=stopwords)
# 生成词云
wc.generate(text)
#保存到本地
wc.to_file(path.join(d, "alice.png"))
#展示
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()
3、着色
"""
使用自定义颜色
===================
使用重新着色方法和自定义着色功能。
"""
import numpy as np
from PIL import Image
from os import path
import matplotlib.pyplot as plt
import random
from wordcloud import WordCloud
def grey_color_func(word, font_size, position, orientation, random_state=None,
**kwargs):
return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)
d = path.dirname(__file__)
# 读取图片
mask = np.array(Image.open(path.join(d, "font.png")))
# 读取文字
text = open(path.join(d, 'a.txt'),encoding="utf-8").read()
wc = WordCloud(max_words=1000, mask=mask, margin=10,
font_path='C:/Windows/Fonts/simsun.ttc', # 设置字体格式,如不设置显示不了中文
random_state=1).generate(text)
# 存储默认的彩色图像
default_colors = wc.to_array()
plt.title("Custom colors")
plt.imshow(wc.recolor(color_func=grey_color_func, random_state=3),
interpolation="bilinear")
wc.to_file("a_new_hope.png") # 保存图片
plt.axis("off") # 关闭轴线和标签
plt.figure() # 设置图片大小
plt.title("Default colors")
plt.imshow(default_colors, interpolation="bilinear")
plt.axis("off")
plt.savefig("./a.png") # 保存
plt.show()
4、
"""
Image-colored wordcloud
=======================
您可以在ImageColorGenerator中实现使用基于图像的着色策略对文字云进行着色,它使用由源图像中的单词占用的区域的平均颜色。
"""
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
d = path.dirname(__file__)
# 读取整个文本
text = open(path.join(d, 'a.txt'),encoding="utf-8").read()
alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))
stopwords = set(STOPWORDS)
stopwords.add("said")
wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,
stopwords=stopwords, max_font_size=40, random_state=42)
# 生成词云
wc.generate(text)
# 从图像创建着色
image_colors = ImageColorGenerator(alice_coloring)
# 显示
plt.imshow(wc, interpolation="bilinear")
plt.axis("off") #不显示坐标尺寸
plt.figure()
# 重新着色词云并显示
# 我们也可以直接在构造函数中给使用:color_func=image_colors
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()#一次绘制三张图
5、表情
"""
表情实例
===============
一个简单的例子,显示如何包含表情符号。 请注意,这个例子似乎不适用于OS X(苹果系统),但是确实如此
在Ubuntu中正常工作
包含表情符号有3个重要步骤:
1) 使用io.open而不是内置的open来读取文本输入。 这确保它被加载为UTF-8
2) 重写词云使用的正则表达式以将文本解析为单词。 默认表达式只会匹配ascii的单词
3) 将默认字体覆盖为支持表情符号的东西。 包含的Symbola字体包括黑色和白色大多数表情符号的白色轮廓。 目前PIL / Pillow库存在的问题似乎可以预防
它在OS X上运行正常(https://github.com/python-pillow/Pillow/issues/1774)。
如果你有问题,试试在Ubuntu上运行
"""
import io
import string
from os import path
from wordcloud import WordCloud
d = path.dirname(__file__)
#使用io.open将文件正确加载为UTF-8非常重要
text = io.open(path.join(d, 'a.txt'),encoding="utf-8").read()
# the regex used to detect words is a combination of normal words, ascii art, and emojis
# 2+ consecutive letters (also include apostrophes), e.x It's
normal_word = r"(?:\w[\w']+)"
# 2+ consecutive punctuations, e.x. :)
ascii_art = r"(?:[{punctuation}][{punctuation}]+)".format(punctuation=string.punctuation)
# a single character that is not alpha_numeric or other ascii printable
emoji = r"(?:[^\s])(?<![\w{ascii_printable}])".format(ascii_printable=string.printable)
regexp = r"{normal_word}|{ascii_art}|{emoji}".format(normal_word=normal_word, ascii_art=ascii_art,
emoji=emoji)
# 生成一个词云图片
# Symbola字体包含大多数表情符号
font_path = 'C:/Windows/Fonts/simsun.ttc'
wordcloud = WordCloud(font_path=font_path, regexp=regexp).generate(text)
# 采用matplotlib方式:展示生成的图片
import matplotlib.pyplot as plt
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
6、jieba分词的例子
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import pickle
from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator
import jieba
# import codecs
# fin = codecs.open('HotelComments.txt',mode = 'r', encoding = 'utf-8')
# print fin.read()
# 第一次运行程序时将分好的词存入文件
# text = ''
# with open('HotelComments.txt') as fin:
# for line in fin.readlines():
# line = line.strip('\n')
# text += ' '.join(jieba.cut(line))
# text += ' '
# fout = open('text.txt','wb')
# pickle.dump(text,fout)
# fout.close()
# 直接从文件读取数据
fr = open('text.txt','rb')
text = pickle.load(fr)
backgroud_Image = plt.imread('girl.jpg')
wc = WordCloud( background_color = 'white', # 设置背景颜色
mask = backgroud_Image, # 设置背景图片
max_words = 2000, # 设置最大现实的字数
stopwords = STOPWORDS, # 设置停用词
font_path = 'C:/Users/Windows/fonts/msyh.ttf',# 设置字体格式,如不设置显示不了中文
max_font_size = 50, # 设置字体最大值
random_state = 30, # 设置有多少种随机生成状态,即有多少种配色方案
)
wc.generate(text)
image_colors = ImageColorGenerator(backgroud_Image)
wc.recolor(color_func = image_colors)
plt.imshow(wc)
plt.axis('off')
plt.show(
参考博客:
https://blog.csdn.net/qq_34337272/article/details/79552929
https://www.cnblogs.com/CQUTWH/p/6129931.html
https://github.com/Snailclimb/python