3 minutes to teach you how to make a simple word cloud with python

Posted by Spoiler on Mon, 06 Jan 2020 07:05:32 +0100

First you need to install three packages:

#Installation: pip install matplotlib
 #Installation: pip install jieba
 #Install pip install wordcloud

1. Make a word cloud of the English alphabet

Design sketch:

Code implementation:

import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud


# 1. Read txt text data
text = open(r'test.txt', "r").read()
#print(text)
# 2. Chinese word segmentation, string generation, default precise mode, without word segmentation, can not directly generate the correct Chinese word cloud
cut_text = jieba.cut(text)
# print(type(cut_text))
# A symbol must be separated from the result of the word break to form a string, otherwise the word cloud cannot be drawn
result = " ".join(cut_text)
#print(result)
# 3. Generate a word cloud image. It is important to note that WordCloud does not support Chinese by default, so you need a downloaded Chinese font library here
# No custom background image: you need to specify the pixel size of the generated word cloud image, default background color is black, uniform text color: mode='RGBA'and colormap='pink'
wc = WordCloud(
        # Set the font, and if you don't specify it, you will get scrambled code
        # Set Background Color
        background_color='white',
        # Set Background Width
        width=500,
        # Set Background Height
        height=350,
        # Maximum font size
        max_font_size=50,
        # Minimum font size
        min_font_size=10,
        mode='RGBA'
        #colormap='pink'
        )
# Generate word clouds
wc.generate(result)
# Save Pictures
wc.to_file(r"wordcloud.png") # Save the drawn word cloud at the set pixel width and height for clearer display than the following program
# 4. Display pictures
# Specify the name of the drawing
plt.figure("jay")
# Show word clouds as pictures
plt.imshow(wc)
# Turn off image coordinate system
plt.axis("off")
plt.show()

The test.txt file contains the following

python python3 is good well bestbast shell cool
Age has reached the end of the beginning of a word. May be guilty in his seems to passing a lot of different life became the appearance of the 
same day; May be backto oneself the paranoid weird belief disillusionment, these days, my mind has been very messy, in my mind constantly. Always 
feel oneself should go to do something, or write something. Twenty years of life trajectory deeply shallow, suddenly feel something, do it.The end 
of our life, and can meet many things really do?During myhood, think lucky money and new clothes are necessary for New Year, but as the advance of 
the age, will be more and more found that those things are optional; Junior high school, thought to have a crush on just means that the real growth,
but over the past three years later, his writing of alumni in peace, suddenly found that isn't really grow up, it seems is not so important; Then 
in high school, think don't want to give vent to out your inner voice can be in the high school children of the feelings in a period, but was event
ually infarction when graduation party in the throat, later again stood on the pitch he has sweat profusely, looked at his thrown a basketball hoops
, suddenly found himself has already can't remember his appearance.

2. Make Chinese Word Cloud

Design sketch:


Code implementation:

#!/usr/bin/Python
# -*- coding: utf-8 -*-
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud, STOPWORDS


###Current File Path
d = path.dirname(__file__)

# Read the whole text.
file = open(path.join(d, 'alice.txt')).read()
##Make a participle
#It's strange to start with a split word put in txt and then open it, but it always doesn't show Chinese
default_mode =jieba.cut(file)
text = " ".join(default_mode)
alice_mask = np.array(Image.open(path.join(d, "1.png")))
stopwords = set(STOPWORDS)
stopwords.add("said")
wc = WordCloud(  
    #Set the font, unspecified code will appear, this font file needs to be downloaded
    font_path=r'/usr/share/fonts/wqy-microhei/wqy-microhei.ttc',  
    background_color="white",   
    max_words=2000,   
    mask=alice_mask,  
    stopwords=stopwords)  
# generate word cloud
wc.generate(text)

# store to file
wc.to_file(path.join(d, "qq_result.jpg"))

# show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()

Where alice.txt file contents:

The Legend Affection of the Family of Red Timber Leaves
 I think Wan Ye and Mao Ball are bound by that chaotic age. In the end, you can only see the future of familiar people. I think it is mostly painful for Wan Ye. Wan Ye can be said to be a mistake even if you forgot to take a bird from a young age or were bullied from a young age.
Strong and pure children, including Black Diamond Green, can also pay as much for their brother, which shows that she deeply loves his brother, so after the suicide incident of Black Diamond Green brother, she actively sought 10,000 leaves to help, and the true friendship gradually emerged, until always, to talk to him
 By the second person Wan Ye must say, is it life. Perhaps the first person in this rank, because their feelings have been well suppressed. Yes, after all, I don't know Wan Ye's understanding of love. Perhaps it just changed to the understanding of being a woman.
What a man can do for a man is to give birth to a few more babies. Now I think it's really simple and rough. The men inside don't like it very much. Similarly, their life is simple: they support the decadent leaf house regardless of everything, except loneliness, but why don't I like it
 He, even the pupil, despised his uncle who saved his life. Since the pill died, I think no one can enter his heart anymore. At the same time, I also feel that Wanye has been watching the tears. Is it really good that her love is biased, if she carefully manages
 Maybe her life will change with the pill. Even if she gives up her comic talent, is it really interesting to talk about pill's life and comic books? Why does it seem to me that a dull and full-fledged experience can be a support or even a good aspiration?
Is her resistance, why she so want to conquer the "Central Plains", but always give her boyfriend's hand to her half-sister, and why her eyes can not reflect a hundred nights, but the last yard uproar, even forced her sister to martyr, sometimes some really
 No idea, but no doubt it will be mysterious. To tell the truth, I don't like pills either, because my sister is still gentle and better, and it seems that she has such an ominous symbol that editors flock off, but I still admire her.
As with friends, daring to correct friends and saying goodbye to them is also quite sacred. I also deeply question the dream and life of that beautiful girl so quickly. Butterfly once laughed about his ideal and life
 I thought it was probably the most normal thing to have a passionate idea about life, but why did the author make her inferior? After all, it's the problem of the world. The students crashed. They said Maybe their brother's tears disappeared from the mountains.
Later, she became the elder daughter of her family. As a support of her family, she was much taller all at once. She was no longer the crazy girl who drove her motorcycle to play with puppies anymore. Then she started a 12-year comic series, so it was a joke or a miracle that she succeeded in her comic books. There were no comics in 12 years.
Rested work, great success, and finally when the comic book is over, she can have a good rest. Remember what she said to her daughter's pupil, "Mom is tired, go to rest." If she hadn't lost her old look, a little girl was a few years old.
Maybe she won't notice that her mother will leave her, even if she hasn't been spoiled properly, even if she looks at her back every day, she will also notice that fur balls are dead after all, death of real yarn, death of butterfly, death of a hundred nights, each time make her life flutter up
 And collapsed in the end.Looking back on Wanye, Black Diamond green is just a typical example from childhood to adulthood. Ha-ha, a girl shouting "picked up" and a girl shouting "bully-loving". After more than ten years, the name has not changed, good friend
 Let's just say that the turning point of Wanye's life might be when we meet the time. This white and fat Whippy must be the home of the decadent leaf family. It seems that we have considered Wanye for a long time. Let Wanye marry into our home directly. After all, what is it for?
Can Ye really bring good luck to the immortal Ye family, but the magic is that she really did it. She made preparations to overcome the oil crisis ahead of time. It is estimated that there are many more, Wan Ye, a very simple child, and finally life and death in the ironmaking furnace.
After that, she thought she had died and lived a long life. She also caused her pupil to have a thorough investigation of her grandmother's suspicion. In fact, if she carefully considered the letter, she would find that it was a duplicate one, one for Ten Thousands Leaves, one for pills, and the same thing was "all at once".
"But different meaning, this man is really a pure man. He gave his right eye for the boiler, and eventually preferred to die with the boiler. You can see that he loves this job. This cold monster, I also want to know if he is the same.
In love with Wanye, I think the readers have some opinions, let alone say. Finally, I must say that the little granddaughter who tells this story from the first perspective is different from her grandmother and mother. She is an ordinary woman. I think this is absolute, freedom, from
 In this article we see the rise and fall of the Family of Red Leaves. With the death of the storyteller, everything changed. In the end, only pupils, loneliness, bags, and busy working fathers were left. The family lost its magical color, along with Wanye.
I thought the story was over, but why did the author want to write about pupils, her love, her outlook on life and the world's hopelessness?At the end, I think of an animation I've seen. It's colorful. I see it clearly
 One of the two things is that the crime of suicide is not more than any other crime, because life is so important that it goes beyond the interpretation of various ethical logic, so is it not the fear of life, and secondly is to never lose the hope of life, the world
 Even if it's ugly or dark, don't give up on her, because there's always someone watching you and watching over you, because there's always a beautiful view in your eyes, because today is not tomorrow anymore, when you open your eyes and find yourself still alive, it's not quite
 Okay, that silk is good enough to support you, that's why people can see the colors.

1.png template content:


Looks like it.

Topics: Python pip REST shell