Python 3.6 使用wordcloud製作詞雲(可設背景圖像)

在python 3.6環境中 使用wordcloud模塊製作詞雲,首先在安裝wordcloud模塊,安裝方法有幾個,可參考安裝方法與可能會遇到的問題

代碼:

#!/usr/bin/env python
# encoding: utf-8

"""
@author: gwu
@software: PyCharm
@time: 2017/3/7 0007 18:11
"""

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

__basePath = '../../data/'
__fileNamePath = u'../../data/wordcloud/love.txt'
__stopWordPath = u'../../data/dict/stopword/stopwords.txt'
__imagePath = u'../../data/image/alice_color.png'
__ttfPath = u'../../data/font/李旭科漫畫體v1.0.ttf'

if __name__ == '__main__':
    d = path.dirname(__file__)

    # Read the whole text.
    text = open(path.join(d, __fileNamePath)).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, __imagePath))

    wc = WordCloud(background_color="black", max_words=2000, mask=alice_coloring,
               stopwords=STOPWORDS.add("said"),
               max_font_size=40, random_state=42)
    # generate word cloud
    wc.generate(text)

    # create coloring from image
    image_colors = ImageColorGenerator(alice_coloring)

    # show
    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()

結果示例:

這裏寫圖片描述

發佈了64 篇原創文章 · 獲贊 221 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章