Python learning 10 lines of code to create a cool word cloud diagram (match the specified graphic shape)


Preface

You must have a question: What is a word cloud?

Word cloud, also called name cloud, is a visually prominent presentation of "keywords" that appear frequently in text data. The rendering of the keywords forms a cloud-like color picture, so that you can understand the main points of the text data at a glance. express meaning.

There are many word cloud renderings on the web page:
Insert image description here


1. What do you need to prepare?

Python code requires the installation of third-party modules pillow (PIL), matplotlib, jieba, wordcloud and numpy
If you encounter problems installing the library, you can refer to the solutions below. Available for testing on windows.
Python learning error: ModuleNotFoundError: No module named 'pandas' Solution
Python learning data analysis and chart application (Part 1) Error: ModuleNotFoundError: No module named 'wordcloud'

2. Code implementation (example)

The code is as follows (example):

#导入matplotlib模块pyplot函数并使用as给函数起个别名plt
import matplotlib.pyplot as plt    
import jieba                       #导入jieba分词模块
import wordcloud                   #导入词云图模块
from wordcloud import ImageColorGenerator
import numpy as np                 #导入numpy模块
from PIL import Image              #从PIL模块中导入Image函数
# 读取文本文件
text = open('elsa.txt','r').read() #elsa.txt可以改成自己的文件
cut_text = jieba.cut(text)         #分词处理
word = ' '.join(cut_text)          #以空格分割文本
#读取图片
pic = np.array(Image.open('aa.png'))
image_colors = ImageColorGenerator(pic)  #生成图片颜色中的颜色
wd = wordcloud.WordCloud(
    mask=pic,                      #背景图形,如果根据图片绘制,则需要设置
    font_path='simhei.ttf',        #可以改成自己喜欢的字体
    background_color='white',      #词云图背景颜色可以换成自己喜欢的颜色
    )
wd.generate(word)                  #生成词云
# 图片颜色渲染词云图的颜色,用color_func指定
plt.imshow(wd.recolor(color_func=image_colors), interpolation='bilinear')
plt.axis('off')#关闭显示x轴、y轴下标
plt.show()

3. Read data

Let's analyze the code block:

1. Imported the drawing module, word cloud generation module and jieba's word segmentation module;

2. Read the local file, use jieba to segment the words, and separate the results of the segmentation with spaces;

3. Read the specified picture graphic file and display the font, color and other parameters for configuration;

4. Generate word cloud and display it

This is just an extremely simple programming, and the effect achieved is also very simple. This is also one of the reasons why I like python, it is simple and clear.

But Python is an open source language. At this time, the characteristics of open source are reflected. Anyone can modify a project to continuously improve the project.

There are many open source projects on Github. There is a word cloud project. You can take a look at the source code:

https://github.com/amueller/word_cloud

We can directly enter the wordcloud.py source code to modify the font and word cloud effects.

4. Result display

Insert image description here

Insert image description here

5. Display of running results after modifying the word cloud color:

color_list=['black','red']
#多种颜色
'''color_list=['LightCoral','RosyBrown','IndianRed','Red','Brown','FireBrick'
            ,'DarkRed','Maroon','Gainsboro','LightGray'
            ,'Silver','DarkGray','Gray','DimGray','Black']'''
colormap=colors.ListedColormap(color_list) #matplotlib色图

Insert image description here
Insert image description here

Summarize

The above is an introduction to Python word cloud generation. The basic steps of word cloud generation are implemented in the source code. In terms of parameter settings, you can set different fonts, shapes and colors according to your own needs, as well as the size of the word cloud. .
Interested friends can check out the many open source projects on Github. There is a word cloud project. You can take a look at the source code: github Address
You can also directly enter the wordcloud.py source code to modify the font and word cloud effects.

Guess you like

Origin blog.csdn.net/u014740628/article/details/129118485