美文网首页ITS·黑客
【Python】实验-词云2

【Python】实验-词云2

作者: 阿凯Awesome | 来源:发表于2017-04-16 23:35 被阅读314次

    以色彩照片为参考来产生词云

    首先,先导入一系列的模块:

    >>>from os import path #从os模块导入path用于查找文件路径
    >>>from PIL import Image #导入照片模块
    >>>import numpy as np #
    >>>from wordcloud import WordCloud,STOPWORDS,ImageColorGenerator
    #导入词云,其中ImageColorGenerator是从照片中取色作为参考的关键
    >>>import matplotlib.pyplot as plt #导入坐标轴

    其次,进行txt文件的读取,照片的读取,对输出照片的参数设置

    >>>d = path.dirname(__file__)
    #此处的__file__保存在py文件中可以直接执行,但在Python环境中,需要换成 '.'
    >>>text = open(path.join(d, 'alice.txt')).read() #读取txt文件
    >>>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")
    #将词云图wc置入坐标轴中,interpolation指插入
    >>>plt.axis("off") #取消坐标轴
    >>>plt.figure() #?

    0

    >>>plt.imshow(wc.recolor(color_func=image_colors),interpolation="bilinear") #这一个对词云重新着色,对应的是照片原色
    >>>plt.axis("off")
    >>>plt.figure()

    1
    展示原照片
    >>>plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear") #展示原照片
    >>>plt.axis("off")
    >>>plt.show()
    2

    相关文章

      网友评论

        本文标题:【Python】实验-词云2

        本文链接:https://www.haomeiwen.com/subject/bjdzattx.html