Learning Python, How to Generate Word Cloud in Python?

Today, we will discuss Word Cloud in PYTHON.


word-cloud


The question that comes here is how to solve or tackle the problem. Whenever we are going to solve a complex problem we need to first divide the problems into sub-problems, and after that find, a solution for each sub-problem, and combine the solution of sub-problems as a final solution. This strategy is called Divide and Conquer. We will use this technique to develop the world cloud in Python.

Step1 -       What is Word Cloud?

The ‘” word cloud” is the “visual representation” of textual data either stored in a text file or some other format like a database file etc. In a word cloud, the size of each word depends upon the frequency of that word in a particular text. The word with greater frequency appears larger than the word with lower frequency. 

Step2 -    Configure Pycharm IDE

   The first step is to install all the necessary libraries used for the word cloud. You can install all the Libraries using the following steps.

  •    Click the File Menu from the Pycharm interface.
  •    Go to settings, and click Python Interpreter.
  •    From the right corner click the “+” button 
  •    A new Screen will appear with a search bar over there
  •    Go to the search bar and install all the packages.

Step3 -    Important Steps

  • Import required libs.
  • Open text file contains some words for which you want to generate a word cloud.
  • Remove punctuations
  • Remove uninteresting words like is, an, the, who, etc.
  • Count frequencies of words
  • Pass the resultant list of words with frequencies to the word cloud object.
  • Display image (plot image) 

Step3 -    Start Coding


#Declare a variables

file_contents=""

file_contents=open("Filename.txt" , 'r').read()

  

In the above code block, we have declared a variable to store file contents and opened the file using that variable. What function do we have to do with that file? We have to only read the text file so we used the. read() function only. Our next focus is to split the file into words so that we can count the frequency of a particular word, here is the code block to split the Text file into words.

And after splitting the data into text write a function that counts the frequencies of words Remember one thing in your mind you have to generate a word cloud but the uninteresting words, and punctuations must be excluded from the text file because we want an appealing word cloud so skip these words here is a dictionary of that word we use to store

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my",

                       "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its",

                       "they", "them", "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be",

                       "been", "being", "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when",

                       "where", "how", "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very",

                       "can", "will", "just"]

 

Our goal is to skip these words, count the frequency and display the word cloud.

def calculate_frequencies(file_contents) #frequency counting using loops

frequencies = {}

taken = []
for letter in punctuation


    file_contents = file_contents.replace(letter, '')

for word in uninteresting_words:

    w = ' ' + word + ' '

    file_contents = file_contents.replace(w, ' ')

for word in file_contents.split():

    if word.lower() not in taken:

        taken.append(word.lower())
        if word not in frequencies:

            frequencies[word] = 1

        else:

            frequencies[word] += 1
 

 

The above method is used to count the frequency, skip the uninteresting words, ignore the punctuations and count the frequency of each word by word.

The next step is to generate the image of the word cloud from the above frequency function

# wordcloud

cloud = wordcloud.WordCloud()

cloud.generate_from_frequencies(frequencies)
return cloud.to_array()

 

   So we are done with everything we need now we are going to display the image of the word cloud by using the following code block.

 # display the image::

# Display your wordcloud image

        myimage = calculate_frequencies(file_contents)

        plt.imshow(myimage, interpolation = 'nearest')

        plt.axis('off')

        plt.show()

 

Step4 -    Putting All together

import matplotlib.pyplot as plt

from wordcloud import wordcloud

import sys

import io

import sys

import numpy as np


#Declare a variable name file_contents:

file_contents=""

file_contents=open("PYTHONPROJECT.txt" , 'r').read()

data =file_contents.split()
def calculate_frequencies(file_contents):

    # Here is a list of punctuations and uninteresting words you can use to process your text

    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

    uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my",

                           "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its",

                           "they", "them", "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be",

                           "been", "being", "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when",

                           "where", "how", "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very",

                           "can", "will", "just"]


    #frequency counting using loops

    frequencies = {}

    taken = []
    for letter in punctuations:

        file_contents = file_contents.replace(letter, '')

    for word in uninteresting_words:

        w = ' ' + word + ' '

        file_contents = file_contents.replace(w, ' ')

    for word in file_contents.split():

        if word.lower() not in taken:

            taken.append(word.lower())
            if word not in frequencies:

                frequencies[word] = 1

            else:

                frequencies[word] += 1

    # wordcloud

    cloud = wordcloud.WordCloud()

    cloud.generate_from_frequencies(frequencies)
    return cloud.to_array()


#display the image::

# Display your wordcloud image
myimage = calculate_frequencies(file_contents)

plt.imshow(myimage, interpolation = 'nearest')

plt.axis('off')

plt.show()



Step5 -     Output

word-cloud


Enjoy and remember

 “I am because we are”.