December 20, 2024

Create a WordCloud using Python

The Raven, by Edgar Allan Poe
The Raven, by Edgar Allan Poe

Here are the instructions I took to create a WordCloud project for the Google IT Automation with Python Course. A word cloud is a simple yet powerful visual representation object for text processing, which shows the most frequent word with bigger and bolder letters, and with different colors. The smaller the size of the word the less important it is. The text I used for this project was The Raven , by Edgar Allan Poe.

The Raven 

by

Edgar Allan Poe


Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore—
While I nodded, nearly napping, suddenly there came a tapping,
As of some one gently rapping, rapping at my chamber door.
“’Tis some visiter,” I muttered, “tapping at my chamber door—
Only this and nothing more.”

Ah, distinctly I remember it was in the bleak December,
And each separate dying ember wrought its ghost upon the floor.
Eagerly I wished the morrow;—vainly I had sought to borrow
From my books surcease of sorrow—sorrow for the lost Lenore—
For the rare and radiant maiden whom the angels name Lenore—
Nameless here for evermore.

And the silken sad uncertain rustling of each purple curtain
Thrilled me—filled me with fantastic terrors never felt before;
So that now, to still the beating of my heart, I stood repeating
“’Tis some visiter entreating entrance at my chamber door—
Some late visiter entreating entrance at my chamber door;
This it is and nothing more.”

Presently my soul grew stronger; hesitating then no longer,
“Sir,” said I, “or Madam, truly your forgiveness I implore;
But the fact is I was napping, and so gently you came rapping,
And so faintly you came tapping, tapping at my chamber door,
That I scarce was sure I heard you”—here I opened wide the door—
Darkness there and nothing more.

Deep into that darkness peering, long I stood there wondering, fearing,
Doubting, dreaming dreams no mortals ever dared to dream before;
But the silence was unbroken, and the stillness gave no token,
And the only word there spoken was the whispered word, “Lenore?”
This I whispered, and an echo murmured back the word, “Lenore!”—
Merely this and nothing more.

Back into the chamber turning, all my soul within me burning,
Soon again I heard a tapping something louder than before.
“Surely,” said I, “surely that is something at my window lattice;
Let me see, then, what thereat is and this mystery explore—
Let my heart be still a moment and this mystery explore;—
’Tis the wind and nothing more.”

Open here I flung the shutter, when, with many a flirt and flutter,
In there stepped a stately Raven of the saintly days of yore.
Not the least obeisance made he; not a minute stopped or stayed he,
But, with mien of lord or lady, perched above my chamber door—
Perched upon a bust of Pallas just above my chamber door—
Perched, and sat, and nothing more.

Then the ebony bird beguiling my sad fancy into smiling,
By the grave and stern decorum of the countenance it wore,
“Though thy crest be shorn and shaven, thou,” I said, “art sure no craven,
Ghastly grim and ancient Raven wandering from the Nightly shore—
Tell me what thy lordly name is on the Night’s Plutonian shore!”
Quoth the Raven, “Nevermore.”

Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning—little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door—
Bird or beast upon the sculptured bust above his chamber door,
With such name as “Nevermore.”

But the Raven, sitting lonely on that placid bust, spoke only
That one word, as if its soul in that one word he did outpour
Nothing farther then he uttered; not a feather then he fluttered—
Till I scarcely more than muttered: “Other friends have flown before—
On the morrow _he_ will leave me, as my Hopes have flown before.”
Then the bird said “Nevermore.”

Startled at the stillness broken by reply so aptly spoken,
“Doubtless,” said I, “what it utters is its only stock and store,
Caught from some unhappy master whom unmerciful Disaster
Followed fast and followed faster till his songs one burden bore—
Till the dirges of his Hope that melancholy burden bore
Of ‘Never—nevermore.’”

But the Raven still beguiling all my sad soul into smiling,
Straight I wheeled a cushioned seat in front of bird and bust and door;
Then, upon the velvet sinking, I betook myself to linking
Fancy unto fancy, thinking what this ominous bird of yore—
What this grim, ungainly, ghastly, gaunt, and ominous bird of yore
Meant in croaking “Nevermore.”

This I sat engaged in guessing, but no syllable expressing
To the fowl whose fiery eyes now burned into my bosom’s core;
This and more I sat divining, with my head at ease reclining
On the cushion’s velvet lining that the lamp-light gloated o’er,
But whose velvet violet lining with the lamp-light gloating o’er
_She_ shall press, ah, nevermore!

Then, methought, the air grew denser, perfumed from an unseen censer
Swung by Seraphim whose foot-falls tinkled on the tufted floor.
“Wretch,” I cried, “thy God hath lent thee—by these angels he hath sent thee
Respite—respite and nepenthe from thy memories of Lenore!
Quaff, oh quaff this kind nepenthe and forget this lost Lenore!”
Quoth the Raven, “Nevermore.”

“Prophet!” said I, “thing of evil!—prophet still, if bird or devil!—
Whether Tempter sent, or whether tempest tossed thee here ashore,
Desolate, yet all undaunted, on this desert land enchanted—
On this home by Horror haunted—tell me truly, I implore—
Is there—_is_ there balm in Gilead?—tell me—tell me, I implore!”
Quoth the Raven, “Nevermore.”

“Prophet!” said I, “thing of evil!—prophet still, if bird or devil!
By that Heaven that bends above us—by that God we both adore—
Tell this soul with sorrow laden if, within the distant Aidenn,
It shall clasp a sainted maiden whom the angels name Lenore—
Clasp a rare and radiant maiden whom the angels name Lenore.”
Quoth the Raven, “Nevermore.”

“Be that our sign of parting, bird or fiend!” I shrieked, upstarting—
“Get thee back into the tempest and the Night’s Plutonian shore!
Leave no black plume as a token of that lie thy soul has spoken!
Leave my loneliness unbroken!—quit the bust above my door!
Take thy beak from out my heart, and take thy form from off my door!”
Quoth the Raven, “Nevermore.”

And the Raven, never flitting, still is sitting, still is sitting
On the pallid bust of Pallas just above my chamber door;
And his eyes have all the seeming of a demon’s that is dreaming
And the lamp-light o’er him streaming throws his shadows on the floor;
And my soul from out that shadow that lies floating on the floor
Shall be lifted—nevermore!

Step 1: Import the necessary libraries


import os
import re
from collections import Counter
from wordcloud import WordCloud

The os module will be used for setting the path of the text file. The re module is used for removing punctuations, the Counter module is used for creating a frequency map of the text file, and the wordcloud module is used for creating the actual WordCloud Image.

Step 2: Open the File

def get_file(filename):
    with open(filename, encoding='utf-8') as fo:
        content = [i.lower().strip() for i in fo]
    return ' '.join(content)

Step 3: Clean the Data

def clean_file(data):
    data = re.sub(r'[^\w\s]', '', data)
    stopwords = ('a', 'an', 'and', 'as', 'at', 'but', 'by', 'from', 'he', 'him', 'i', 'is', 'my', 'of', 'or',
                 'on', 'said', 'that', 'the', 'there', 'this', 'to', 'with')
    return Counter([word for word in data.split() if word not in stopwords])

We are using the re module to remove all punctuations from the text. Next, we remove all non-interesting words as seen in the tuple stopwords in the code above. Finally, we use the Counter module to create a frequency map of the new list and return it.

Step 4: Generate the WordCloud

def generate_wordcloud(data):
    return WordCloud(height=800, width=1200).generate_from_frequencies(data)

Now we generate the WordCloud. Here I am creating an WordCloud image that is 800×1200 pixels in dimension.

Step 5: Save the Image File

def save_wordcloud(data, filename):
    data.to_file(os.path.join(filename))
    print(f'{filename} has been successfully saved.')

Finally, we save the WordCloud image. Here the os module is used to create a complete path.

The Complete Code

Now lets take a look at the complete code.

#!/usr/bin/env python3

import os
import re
from collections import Counter
from wordcloud import WordCloud


def get_file(filename):
    with open(filename, encoding='utf-8') as fo:
        content = [i.lower().strip() for i in fo]
    return ' '.join(content)


def clean_file(data):
    data = re.sub(r'[^\w\s]', '', data)
    stopwords = ('a', 'an', 'and', 'as', 'at', 'but', 'by', 'from', 'he', 'him', 'i', 'is', 'my', 'of', 'or',
                 'on', 'said', 'that', 'the', 'there', 'this', 'to', 'with')
    return Counter([word for word in data.split() if word not in stopwords])


def generate_wordcloud(data):
    return WordCloud(height=800, width=1200).generate_from_frequencies(data)


def save_wordcloud(data, filename):
    data.to_file(os.path.join(filename))
    print(f'{filename} has been successfully saved.')


def main():
    raven_path = os.path.join('the_raven.txt')
    raven_file = get_file(raven_path)

    process_file = clean_file(raven_file)
    raven_cloud = generate_wordcloud(process_file)
    save_wordcloud(raven_cloud, 'raven_cloud.jpg')


if __name__ == '__main__':
    main()

Final Results

The Raven, WordCloud. By Edgar Allen Poe

Leave a Reply

Your email address will not be published.