Python制作簡(jiǎn)單的詞云

個(gè)人博客

http://www.milovetingting.cn

背景圖

mask.jpg

效果圖

sample.jpg

代碼

from os import path
import jieba
from wordcloud import WordCloud
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt


def handle_data():
    """
    處理文本數(shù)據(jù)
    :return:
    """
    # 讀取數(shù)據(jù)
    with open("data.txt", "r") as f:
        txt = f.read()

    # 去除無效數(shù)據(jù)
    re_move = [",", "。", " ", '\n', '\xa0']
    for i in re_move:
        txt = txt.replace(i, " ")

    # 使用精確分詞模式
    word = jieba.lcut(txt)

    # 保存數(shù)據(jù)
    with open("data_handled.txt", 'w') as file:
        for i in word:
            file.write(str(i) + ' ')


def generate_image():
    """
    生成圖片
    :return:
    """
    # 讀取數(shù)據(jù)
    with open("data_handled.txt", "r") as file:
        txt = file.read()

    # 圖片路徑
    d = path.dirname(__file__)

    # 生成mask
    mask = np.array(Image.open(path.join(d, "mask.jpg")))

    # 生成word
    word = WordCloud(
        background_color="white",
        width=800,
        height=800,
        mask=mask,
        # 字體路徑,WordCloud默認(rèn)不支持中文,這里的SimHei.ttf需要下載放到系統(tǒng)字體庫(kù)目錄下
        font_path='SimHei.ttf'
    ).generate(txt)

    # 保存圖片
    word.to_file('world_cloud.png')

    # 使用plt庫(kù)顯示圖片
    plt.imshow(word)

    plt.axis("off")

    plt.show()


if __name__ == '__main__':
    handle_data()
    generate_image()

參考

https://blog.csdn.net/loveyouandc/article/details/88193641

https://www.cnblogs.com/djdjdj123/p/12153603.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容