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="	")

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