Python数据挖掘-词云美化

1、语料库构建

由于不像之前是对很多个文件进行词频统计,所以不需要使用os.walk()方法遍历每一个文件;

只需使用codecs.open()打开相应的文件,(记得close);

然后使用jieba模块中的load_userdict()方法导入词库

import jieba
import numpy
import codecs
import pandas

file=codecs.open(
    "C:\\Users\\Jw\\Desktop\\python_work\\Python数据挖掘实战课程课件\\2.5\\红楼梦.txt",
    "r",encoding="utf-8")

content=file.read()
file.close

jieba.load_userdict("C:\\Users\\Jw\\Desktop\\python_work\\Python数据挖掘实战课程课件\\2.5\\红楼梦词库.txt")

segments=[]
segs=jieba.cut(content)
for seg in segs:
    if len(seg)>1:
        segments.append(seg)

segmentDF=pandas.DataFrame({
                    "segment":segments})

 

2、移除停用词

首先是读出停用词库,然后通过DataFrame中isin(),取反~的方法来移除停用词

将筛选后的分词进行统计

stopwords=pandas.read_csv(
        "D:\\Python\\Python数据挖掘\\Python数据挖掘实战课程课件\\2.5\\StopwordsCN.txt",
        encoding="utf-8",
        index_col=False,
        quoting=3,
        sep="\t")

segmentDF=segmentDF[
    ~segmentDF.segment.isin(stopwords.stopword)]

segStat=segmentDF.groupby(
        by=["segment"]
        )["segment"].agg({
        "计数":numpy.size
        }).reset_index().sort(
        columns=["计数"],
        ascending=False)
segStat.head(100)

 

3、普通词云的绘制

from wordcloud import WordCloud
import matplotlib.pyplot as plt

wordcloud=WordCloud(
    font_path="D:\\Python\\爱数圈书籍\\Python数据挖掘\\Python数据挖掘实战课程课件\\2.4\\simhei.ttf",
    background_color="black")

words=segStat.set_index("segment").to_dict()

wordcloud=wordcloud.fit_words(words["计数"])
plt.imshow(wordcloud)
plt.close()

 

4、词云美化

导入scipy.misc中的imread函数,该函数时导入图片,用于词云

从wordcloud模块中导入WordCloud,ImageColorGenerator函数

ImageColorGenerator是提取图片颜色

from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator

#导入图片
bimg=imread("D:\\Python\\爱数圈书籍\\Python数据挖掘\\Python数据挖掘实战课程课件\\2.5\\贾宝玉.png")

wordcloud=WordCloud(
        background_color="white",
        mask=bimg,font_path="D:\\Python\\爱数圈书籍\\Python数据挖掘\\Python数据挖掘实战课程课件\\2.4\\simhei.ttf")
#适配词云图
wordcloud=wordcloud.fit_words(words["计数"])
#图云颜色
bimgColors=ImageColorGenerator(bimg)

plt.axis("off")
plt.imshow(wordcloud.recolor(color_func=bimgColors))
plt.show()

bimg=imread("D:\\Python\\爱数圈书籍\\Python数据挖掘\\Python数据挖掘实战课程课件\\2.5\\贾宝玉2.png")

wordcloud=WordCloud(
    background_color="white",
        mask=bimg,font_path="D:\\Python\\爱数圈书籍\\Python数据挖掘\\Python数据挖掘实战课程课件\\2.4\\simhei.ttf")

wordcloud = wordcloud.fit_words(words['计数'])

plt.figure(
    num=None,figsize=(8,6),dpi=80,facecolor="w",edgecolor="k")

bimgColors=ImageColorGenerator(bimg)
plt.axis("off")
plt.imshow(wordcloud.recolor(color_func=bimgColors))
plt.show()

 

转载于:https://www.cnblogs.com/U940634/p/9736129.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值