wordcloud词云使用

# -*- coding: utf-8 -*-
"""
Created on Wed Aug 16 13:53:52 2017

@author: gzs10227
"""

from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import jieba
import jieba.analyse
import re
from collections import Counter

plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']




d = path.dirname(u'E:/廖庆豪/2017/201708/文本分析/')

text = open(path.join(d, 'ngc.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, "test.jpg"))

wc = WordCloud(background_color="black", #背景颜色max_words=2000,# 词云显示的最大词数
font_path='E:/Anaconda2/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/Microsoft YaHei.ttf',
mask=alice_coloring,#设置背景图片
stopwords=STOPWORDS.add("said"),
max_font_size=40, #字体最大值
random_state=42)




text = re.sub(r'\[b\].*?\[\/b\]','',text)
text = re.sub(r'\[quote\].*?\[\/pid\]','',text)
text = re.sub(r'\[img\].*?\[\/img\]','',text)
text = re.sub(r'\[align=center\].*?\[list\]','',text)
text = re.sub(r'\[quote\].*?\[\/quote\]','',text)
text = re.sub(r'\[url\].*?\[\/url\]','',text)
text = re.sub(r'\[s:.*?\]','',text)
text = re.sub(r'\[.*?\]','',text)
text = text.replace('\t','').replace('\n','').replace(' ','')

text = re.sub(r'[,:.!=?#%()#+-\/0-9]+','',text)
    
ci = [i for i in jieba.cut(text) if len(i)>1]

data = dict(Counter(ci))

ci_list = []

for k,v in data.items():
    temp = (k,v)
    ci_list.append(temp)
    


# 生成词云, 可以用generate输入全部文本(中文不好分词),也可以我们计算好词频后使用generate_from_frequencies函数
wc.generate(text)

wc.generate_from_frequencies(data)
# 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, "tt.png"))

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值