The Wayback Machine - https://web.archive.org/web/20240830065324/https://www.geeksforgeeks.org/generating-word-cloud-python/
Open In App

Generating Word Cloud in Python

Last Updated : 05 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites.

For generating word cloud in Python, modules needed are – matplotlib, pandas and wordcloud. To install these packages, run the following commands :

pip install matplotlib
pip install pandas
pip install wordcloud

The dataset used for generating word cloud is collected from UCI Machine Learning Repository. It consists of YouTube comments on videos of popular artists. 
Dataset Link : https://archive.ics.uci.edu/ml/machine-learning-databases/00380/

Below is the implementation : 

Python3




# Python program to generate WordCloud
 
# importing all necessary modules
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import pandas as pd
 
# Reads 'Youtube04-Eminem.csv' file
df = pd.read_csv(r"Youtube04-Eminem.csv", encoding ="latin-1")
 
comment_words = ''
stopwords = set(STOPWORDS)
 
# iterate through the csv file
for val in df.CONTENT:
     
    # typecaste each val to string
    val = str(val)
 
    # split the value
    tokens = val.split()
     
    # Converts each token into lowercase
    for i in range(len(tokens)):
        tokens[i] = tokens[i].lower()
     
    comment_words += " ".join(tokens)+" "
 
wordcloud = WordCloud(width = 800, height = 800,
                background_color ='white',
                stopwords = stopwords,
                min_font_size = 10).generate(comment_words)
 
# plot the WordCloud image                      
plt.figure(figsize = (8, 8), facecolor = None)
plt.imshow(wordcloud)
plt.axis("off")
plt.tight_layout(pad = 0)
 
plt.show()


Output : 
 

The above word cloud has been generated using Youtube04-Eminem.csv file in the dataset. One interesting task might be generating word clouds using other csv files available in the dataset.

Advantages of Word Clouds : 

  1. Analyzing customer and employee feedback.
  2. Identifying new SEO keywords to target.

Drawbacks of Word Clouds : 

  1. Word Clouds are not perfect for every situation.
  2. Data should be optimized for context.

Reference : https://en.wikipedia.org/wiki/Tag_cloud



Similar Reads

Generating Word Cloud in Python | Set 2
Prerequisite: Generating Word Cloud in Python | Set - 1Word Cloud is a data visualization technique used for representing text data in which the size of each word indicates its frequency or importance. Significant textual data points can be highlighted using a word cloud. Word clouds are widely used for analyzing data from social network websites.F
5 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
Converting WhatsApp chat data into a Word Cloud using Python
Let us see how to create a word cloud using a WhatsApp chat file. Convert the WhatsApp chat file from .txt format to .csv file. This can be done using Pandas. Create a DataFrame which read the .txt file. The .txt file had no columns like it is in an .csv file. Then, split the data into columns by separating them and giving each column a name. The f
4 min read
Google Cloud Platform - Running Different Versions of Python on Google Cloud Run
Problem Statement: Rinki works for StoreCraft(Say) as a site reliability engineer, where she's on-call maintaining their custom storefront. StoreCraft's systems are developed in-house in Python and have been running on virtual machines for years, a set up that evolved as StoreCraft's businesses did. These virtual machines use slightly different ver
3 min read
Generating random Id's in Python
In python there are different ways to generate id's. Let's see how different types of Id's can be generated using python without using inbuilt Python libraries. 1. Generating Random Integer as Ids' Code #1 : Print 10 random values of numbers between 1 and 100. C/C++ Code # Python3 code to demonstrate the # random generation of Integer id's import r
2 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness
3 min read
Pandas - Generating ranges of timestamps using Python
A timestamp is a string of characters or encrypted or encoded data that identifies the time and date of an event, usually indicating the time and date of day, and is often accurate to a fraction of a second. timestamps are used to maintain track of information. When information was created, transmitted, edited, or removed, it was given a timestamp.
3 min read
Generating Beautiful Code Snippets using Python
When creating technical documentation or tutorials, it can be helpful to include images of code snippets to illustrate specific examples or concepts. However, taking a screenshot of a code file can look unprofessional and hard to read. This article will explore how to convert programming code into beautiful image snippets in Python using the librar
3 min read
Generating meshes in Python
In computer graphics and scientific computing, the mesh is an arrangement of points, lines, and surfaces that outline the shape and structure of a 3D object or surface. Making meshes is a critical process in several industries, such as 3D modelling, simulation, visualization, and gaming. In this article, we'll explore various libraries and techniqu
5 min read
Generating Strong Password using Python
Having a weak password is not good for a system that demands high confidentiality and security of user credentials. It turns out that people find it difficult to make up a strong password that is strong enough to prevent unauthorized users from memorizing it. This article uses a mixture of numbers, alphabets, and other symbols found on the computer
3 min read
Reading and Generating QR codes in Python using QRtools
This article aims to introduce the use of the python library: qrtools. This library can be used to both read QR codes and generate them. What are QR codes? QR code, or quick response code, is a trademark for a type of 2 dimensional barcode. 2 dimensional barcodes are similar to one dimensional barcodes, but can store more information per unit area.
5 min read
Generating hash id's using uuid3() and uuid5() in Python
Python's UUID class defines four functions and each generates different version of UUIDs. Let's see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID's taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are :
2 min read
Generating subarrays using recursion
Given an array, generate all the possible subarrays of the given array using recursion. Examples: Input : [1, 2, 3] Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] Input : [1, 2] Output : [1], [1, 2], [2] We have discussed iterative program to generate all subarrays. In this post, recursive is discussed. Approach: We use two pointers start and en
6 min read
Generating all possible Subsequences using Recursion including the empty one.
Given an array. The task is to generate and print all of the possible subsequences of the given array using recursion. Examples: Input : [1, 2, 3] Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3], [] Input : [1, 2] Output : [2], [1], [1, 2], [] Approach: For every element in the array, there are two choices, either to include it in the sub
5 min read
Pafy - Generating File Name of Stream
In this article we will see how we can generate file name of given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. File name is the t
2 min read
Generating Basic Discrete Time Signals
Generating basic discrete-time signals for Discrete-Time Signal ProcessingUnit Step, Unit Impulse, Unit Ramp, exponential signals are very commonly used signals in signal processing to perform various operations. Unit step signal is given byUnit impulse signal is given byUnit ramp signal is given byExponential signal is given by Examples: Input : U
2 min read
Generating dynamic URLs in Flask
Prerequisites: Basics of Flask When creating an application, it's quite cumbersome to hard-code each URL. A better way to resolve this problem is through building Dynamic URLs. Let us briefly understand the meaning of a few common terms first. Dynamic Routing: It is the process of getting dynamic data(variable names) in the URL and then using it.Va
3 min read
Generating Random Integers in Pandas Dataframe
Pandas is the most popular Python library that is used for data analysis. It provides highly optimized performance with back-end source code that is purely written in C or Python. Here we will see how to generate random integers in the Pandas datagram. We will be using the numpy.random.randint() method to generate random integers. Generating Random
3 min read
Python | Word Similarity using spaCy
Word similarity is a number between 0 to 1 which tells us how close two words are, semantically. This is done by finding similarity between word vectors in the vector space. spaCy, one of the fastest NLP libraries widely used today, provides a simple method for this task. spaCy's Model - spaCy supports two methods to find word similarity: using con
2 min read
Second most repeated word in a sequence in Python
Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. (Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"geeks", "for", "geeks", "for", "geeks", "aaa"} Outp
4 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Python | Reverse each word in a sentence
Given a long sentence, reverse each word of the sentence individually in the sentence itself. Examples: Input : Geeks For Geeks is good to learn Output : skeeG roF skeeG si doog ot nrael Input : Split Reverse Join Output : tilpS esreveR nioJ We shall use Python's built in library function to reverse each word individually in the string itself. Prer
3 min read
Find frequency of each word in a string in Python
Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi Aeroplane Taxi Bus" Output : frequency of Train is
7 min read
Python | TextBlob.Word.spellcheck() method
With the help of TextBlob.Word.spellcheck() method, we can check the word if that word have spelling mistake by using TextBlob.Word.spellcheck() method. Syntax : TextBlob.Word.spellcheck() Return : Return the word with correctness accuracy. Example #1 : In this example we can say that by using TextBlob.Word.spellcheck() method, we are able to get t
1 min read
Python - Separate first word from String
Sometimes, while working with Python strings, we can have a problem in which we need to separate the first word from the entire string. This can have possible applications in many domains such as day-day and web-development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is the brute force way in which t
7 min read
How to obtain the line number in which given word is present using Python?
To obtain the line number from the file where the given word is present, create a list in which each index contains the content of each line with Python. To do so follow the below instruction. Get Line Number of Certain Phrase in a Text fileBelow are the methods that we will cover in this article. Using IterationUsing EnumerateInput file: File1.txt
3 min read
How to replace a word in excel using Python?
Excel is a very useful tool where we can have the data in the format of rows and columns. We can say that before the database comes into existence, excel played an important role in the storage of data. Nowadays using Excel input, many batch processing is getting done. There may be the requirement of replacing text in Excel sheet is always there as
3 min read
Speak the meaning of the word using Python
The following article shows how by the use of two modules named, pyttsx3 and PyDictionary, we can make our system say out the meaning of the word given as input. It is module which speak the meaning when we want to have the meaning of the particular word. Modules neededPyDictionary: It is a Dictionary Module for Python 2-3 to get meanings, translat
2 min read
Pulling a random word or string from a line in a text file in Python
File handling in Python is really simple and easy to implement. In order to pull a random word or string from a text file, we will first open the file in read mode and then use the methods in Python's random module to pick a random word. There are various ways to perform this operation: This is the text file we will read from: Method 1: Using rando
2 min read
Generate Word Clouds Of Any Shape In Python
In this article, we will discuss how to create word clouds of any shape in Python. The term WordCloud refers to a data visualization technique for showing text data in which the size of each word indicates its frequency or relevance. To create a word cloud of any shape, use Python's Matplotlib, word cloud, NumPy, and PIL packages. Stepwise Implemen
6 min read
Article Tags :
Practice Tags :