Personal blog

www.milovetingting.cn

background

rendering

code

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() :
    """ Processing text data :return: """
    # fetch data
    with open("data.txt"."r") as f:
        txt = f.read()

    # Remove invalid data
    re_move = [","."。"."".'\n'.'\xa0']
    for i in re_move:
        txt = txt.replace(i, "")

    # Use exact word segmentation patterns
    word = jieba.lcut(txt)

    # Save data
    with open("data_handled.txt".'w') as file:
        for i in word:
            file.write(str(i) + ' ')


def generate_image() :
    """
    生成图片
    :return:
    """
    # fetch data
    with open("data_handled.txt"."r") as file:
        txt = file.read()

    # Image path
    d = path.dirname(__file__)

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

    # generate word
    word = WordCloud(
        background_color="white",
        width=800,
        height=800,
        mask=mask,
        # font path,WordCloud default does not support Chinese, here SimHei. TTF need to download the system font library directory
        font_path='SimHei.ttf'
    ).generate(txt)

    # Save images
    word.to_file('world_cloud.png')

    # Use the PLT library to display images
    plt.imshow(word)

    plt.axis("off")

    plt.show()


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

Copy the code

reference

Blog.csdn.net/loveyouandc…

www.cnblogs.com/djdjdj123/p…