The Wayback Machine - https://web.archive.org/web/20241126205058/https://www.geeksforgeeks.org/text-preprocessing-in-python-set-1/
Open In App

Text Preprocessing in Python

Last Updated : 02 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Text Processing pertains to the analysis of text data using a programming language such as Python. Text Processing is an essential task in NLP as it helps to clean and transform raw data into a suitable format used for analysis or modeling.

In this article, we will learn by using various Python Libraries and Techniques that are involved in Text Processing.

Prerequisites: Introduction to NLP

Whenever we have textual data, we need to apply several processing and pre-processing steps to the data to transform words into numerical features that work with machine learning algorithms. The pre-processing steps for a problem depend mainly on the domain and the problem itself, hence, we don’t need to apply all steps to every problem. 
In this article, we are going to see text preprocessing in Python. We will be using the NLTK (Natural Language Toolkit) library here.  

Python
# import the necessary libraries
import nltk
import string
import re

Text Lowercase

We lowercase the text to reduce the size of the vocabulary of our text data.
 

Python
def text_lowercase(text):
    return text.lower()

input_str = "Hey, did you know that the summer break is coming? Amazing right !! It's only 5 more days !!";
text_lowercase(input_str)

Example: 
 

Input: “Hey, did you know that the summer break is coming? Amazing right!! It’s only 5 more days!!” 
Output: “hey, did you know that the summer break is coming? amazing right!! it’s only 5 more days!!” 
 

Remove numbers

We can either remove numbers or convert the numbers into their textual representations. 
We can use regular expressions to remove the numbers. 
 

Python
# Remove numbers
def remove_numbers(text):
    result = re.sub(r'\d+', '', text)
    return result

input_str = "There are 3 balls in this bag, and 12 in the other one."
remove_numbers(input_str)

Example: 

Input: “There are 3 balls in this bag, and 12 in the other one.” 
Output: ‘There are balls in this bag, and in the other one.’ 
 

We can also convert the numbers into words. This can be done by using the inflect library.

Python
# import the inflect library
import inflect
p = inflect.engine()

# convert number into words
def convert_number(text):
    # split string into list of words
    temp_str = text.split()
    # initialise empty list
    new_string = []

    for word in temp_str:
        # if word is a digit, convert the digit
        # to numbers and append into the new_string list
        if word.isdigit():
            temp = p.number_to_words(word)
            new_string.append(temp)

        # append the word as it is
        else:
            new_string.append(word)

    # join the words of new_string to form a string
    temp_str = ' '.join(new_string)
    return temp_str

input_str = 'There are 3 balls in this bag, and 12 in the other one.'
convert_number(input_str)

Example: 
 

Input: “There are 3 balls in this bag, and 12 in the other one.” 
Output: “There are three balls in this bag, and twelve in the other one.” 

Remove punctuation

We remove punctuations so that we don’t have different forms of the same word. If we don’t remove the punctuation, then been. been, been! will be treated separately.
 

Python
# remove punctuation
def remove_punctuation(text):
    translator = str.maketrans('', '', string.punctuation)
    return text.translate(translator)
input_str = "Hey, did you know that the summer break is coming? Amazing right !! It's only 5 more days !!"
remove_punctuation(input_str)

Example: 
 

Input: “Hey, did you know that the summer break is coming? Amazing right!! It’s only 5 more days!!” 
Output: “Hey did you know that the summer break is coming Amazing right Its only 5 more days” 
 

Remove whitespace

We can use the join and split function to remove all the white spaces in a string.
 

Python
# remove whitespace from text
def remove_whitespace(text):
    return  " ".join(text.split())
input_str = "we don't need   the given questions"
remove_whitespace(input_str)

Example: 
 

Input: "   we don't need   the given questions"
Output: "we don't need the given questions"

Remove default stopwords

Stopwords are words that do not contribute to the meaning of a sentence. Hence, they can safely be removed without causing any change in the meaning of the sentence. The NLTK library has a set of stopwords and we can use these to remove stopwords from our text and return a list of word tokens.

Example:

Python
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

# remove stopwords function
def remove_stopwords(text):
    stop_words = set(stopwords.words("english"))
    word_tokens = word_tokenize(text)
    filtered_text = [word for word in word_tokens if word not in stop_words]
    return filtered_text

example_text = "This is a sample sentence and we are going to remove the stopwords from this."
remove_stopwords(example_text)

Example: 
 

Input: “This is a sample sentence and we are going to remove the stopwords from this” 
Output: [‘This’, ‘sample’, ‘sentence’, ‘going’, ‘remove’, ‘stopwords’] 
 

Stemming

Stemming is the process of getting the root form of a word. Stem or root is the part to which inflectional affixes (-ed, -ize, -de, -s, etc.) are added. The stem of a word is created by removing the prefix or suffix of a word. So, stemming a word may not result in actual words.

Example: 

books      --->    book
looked     --->    look
denied     --->    deni
flies      --->    fli


 


 


If the text is not in tokens, then we need to convert it into tokens. After we have converted strings of text into tokens, we can convert the word tokens into their root form. There are mainly three algorithms for stemming. These are the Porter Stemmer, the Snowball Stemmer and the Lancaster Stemmer. Porter Stemmer is the most common among them.
 

Python
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
stemmer = PorterStemmer()

# stem words in the list of tokenized words
def stem_words(text):
    word_tokens = word_tokenize(text)
    stems = [stemmer.stem(word) for word in word_tokens]
    return stems

text = 'data science uses scientific methods algorithms and many types of processes'
stem_words(text)

Example: 

Input: ‘data science uses scientific methods algorithms and many types of processes’ 
Output: [‘data’, ‘scienc’, ‘use’, ‘scientif’, ‘method’, ‘algorithm’, ‘and’, ‘mani’, ‘type’, ‘of’, ‘process’] 

Lemmatization

Lemmatization is a natural language processing (NLP) technique that reduces a word to its root form. This can be helpful for tasks such as text analysis and search, as it allows you to compare words that are related but have different forms. 

Python
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
import nltk # Import nltk

nltk.download('punkt') # Download the 'punkt' resource
nltk.download('wordnet') # Download the 'wordnet' resource 

lemmatizer = WordNetLemmatizer()

def lemma_words(text):
    word_tokens = word_tokenize(text)
    lemmas = [lemmatizer.lemmatize(word) for word in word_tokens]
    return lemmas
  
input_str = "data science uses scientific methods algorithms and many types of processes"
lemma_words(input_str)

Example: 

Input: ‘data science uses scientific methods algorithms and many types of processes’ 
Output:

[‘data’,
‘science’,
‘us’,
‘scientific’,
‘method’,
‘algorithm’,
‘and’,
‘many’,
‘type’,
‘of’,
‘process’]

FAQs on Text-Processing in Python

Q1. What are the testing frameworks are commonly used for text processing in python?

  • unittest: There are some built-in testing frameworks in Python
  • pytest: This is the third-party testing frameworks that are known for its simplicity.
  • nose2: this is nose testing frameworks with additional features.
  • doctest: A module for testing docstrings by running examples embedded in documentation.

Q2. How do i run tests in Python?

You can run tests using the following commands:

  • For unittest: ‘python -m unittest <test_module>’
  • For Pytest: ‘pytest<test_module>

Q3. How can i mock objects in Python tests?

Python provides the ‘unittest.mock’ module, that allow to create mock objects for testing.

Q4. How do i write basic test in Python?

You can create a test class which inherits from ‘unittest.TestCase’ and write test methods within it. You can write function name and start with “test_” to use assertions just to check output that are expected.



Previous Article
Next Article

Similar Reads

Python - Preprocessing of Tamil Text
Preprocessing is the major part of Natural Language Processing. In order to classify any text with high accuracy, cleaned data plays a major role. So, the first step in NLP before analyzing or classifying is preprocessing of data. Many python libraries support preprocessing for the English language. But for the Tamil Language, there are very few pr
3 min read
Text Preprocessing in Python | Set 2
Text Preprocessing is one of the initial steps of Natural Language Processing (NLP) that involves cleaning and transforming raw data into suitable data for further processing. It enhances the quality of the text makes it easier to work and improves the performance of machine learning models. In this article, we will look at some more advanced text
4 min read
Text Preprocessing in NLP
Natural Language Processing (NLP) has seen tremendous growth and development, becoming an integral part of various applications, from chatbots to sentiment analysis. One of the foundational steps in NLP is text preprocessing, which involves cleaning and preparing raw text data for further analysis or model training. Proper text preprocessing can si
6 min read
YouTube Data Scraping, Preprocessing and Analysis using Python
YouTube is one of the oldest and most popular video distribution platforms in the world. We can't even imagine the video content available here. It has billion of users and viewers, which keeps on increasing every passing minute. Since its origins, YouTube and its content have transformed very much. Now we have SHORTS, likes, and many more features
5 min read
ML | Data Preprocessing in Python
In order to derive knowledge and insights from data, the area of data science integrates statistical analysis, machine learning, and computer programming. It entails gathering, purifying, and converting unstructured data into a form that can be analysed and visualised. Data scientists process and analyse data using a number of methods and tools, su
7 min read
LughaatNLP: A Powerful Urdu Language Preprocessing Library
In recent years, natural language processing (NLP) has witnessed tremendous growth. Now researchers and developers are exploring various languages beyond English. Urdu is one of the widely spoken languages in South Asia. To help with Urdu language processing tasks, a new and robust preprocessing library called LughaatNLP has arisen as a vital tool
9 min read
Using ColumnTransformer in Scikit-Learn for Data Preprocessing
Data preprocessing is a critical step in any machine learning workflow. It involves cleaning and transforming raw data into a format suitable for modeling. One of the challenges in preprocessing is dealing with datasets that contain different types of features, such as numerical and categorical data. Scikit-learn's ColumnTransformer is a powerful t
15 min read
Difference Between StandardScaler and Normalizer in sklearn.preprocessing
Preprocessing step in machine learning task that helps improve the performance of models. Two commonly used techniques in the sklearn.preprocessing module are StandardScaler and Normalizer. Although both are used to transform features, they serve different purposes and apply different methods. In this article, we will explore the differences betwee
3 min read
Text to text Transfer Transformer in Data Augmentation
Do you want to achieve 'the-state-of-the-art' results in your next NLP project?Is your data insufficient for training the machine learning model?Do you want to improve the accuracy of your machine learning model with some extra data? If yes, all you need is Data Augmentation. Whether you are building text classification, summarization, question ans
8 min read
Text-To-Speech changing voice in Python
There are several APIs available to convert text to speech in python. One such APIs is the Python Text to Speech API commonly known as the pyttsx3 API. pyttsx3 is a very easy to use tool which converts the text entered, into audio. Installation To install the pyttsx3 API, open terminal and write pip install pyttsx3 This library is dependent on win3
3 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks review-team@geeksforgeeks.org review-team@geeksforgeeks.org GfG is a portal for gee
1 min read
Python - Efficient Text Data Cleaning
Gone are the days when we used to have data mostly in row-column format, or we can say Structured data. In present times, the data being collected is more unstructured than structured. We have data in the form of text, images, audio etc and the ratio of Structured to Unstructured data has decreased over the years. Unstructured data is increasing at
7 min read
Python | Tokenize text using TextBlob
TextBlob module is a Python library and offers a simple API to access its methods and perform basic NLP tasks. It is built on the top of NLTK module. Install TextBlob using the following commands in terminal: pip install -U textblob python -m textblob.download_corpora This will install TextBlob and download the necessary NLTK corpora. The above ins
3 min read
Python | Splitting Text and Number in string
Sometimes, we have a string, which is composed of text and number (or vice-versa), without any specific distinction between the two. There might be a requirement in which we require to separate the text from the number. Let's discuss certain ways in which this can be performed. Method #1 : Using re.compile() + re.match() + re.groups() The combinati
7 min read
Python - Count occurrences of each word in given text file
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the word is already present in the dictionary we increm
4 min read
Python | Merge two text files
Given two text files, the task is to merge the data and store in a new text file. Let's see how can we do this task using Python. To merge two files in Python, we are asking user to enter the name of the primary and second file and make a new file to put the unified content of the two data into this freshly created file. In order to do this task, w
2 min read
Python | Create an empty text file with current date as its name
In this article, we will learn how to create a text file names as the current date in it. For this, we can use now() method of datetime module. The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute
1 min read
Python | Convert image to text and then to speech
Our goal is to convert a given text image into a string of text, saving it to a file and to hear what is written in the image through audio. For this, we need to import some Libraries Pytesseract(Python-tesseract) : It is an optical character recognition (OCR) tool for python sponsored by google. pyttsx3 : It is an offline cross-platform Text-to-Sp
2 min read
Python | Finding 'n' Character Words in a Text File
This article aims to find words with a certain number of characters. In the code mentioned below, a Python program is given to find the words containing three characters in the text file. Example Input: Hello, how are you ? , n=3 Output: how are you Explanation: Output contains every character of the of length 3 from the input file.Input File: File
3 min read
Text detection using Python
Python language is widely used for modern machine learning and data analysis. One can detect an image, speech, can even detect an object through Python. For now, we will detect whether the text from the user gives a positive feeling or negative feeling by classifying the text as positive, negative, or neutral. In the code, Vader sentiment analysis
4 min read
Python program to Reverse a single line of a text file
Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer science portal User choice = 0 Output: geek a is This
2 min read
Python | Text Summarizer
Today various organizations, be it online shopping, government and private sector organizations, catering and tourism industry or other institutions that offer customer services are concerned about their customers and ask for feedback every single time we use their services. Consider the fact, that these companies may be receiving enormous amounts
5 min read
Python - Extract hashtags from text
A hashtag is a keyword or phrase preceded by the hash symbol (#), written within a post or comment to highlight it and facilitate a search for it. Some examples are: #like, #gfg, #selfie We are provided with a string containing hashtags, we have to extract these hashtags into a list and print them. Examples: Input : GeeksforGeeks is a wonderful #we
3 min read
Python - Substituting patterns in text using regex
Regular Expression (regex) is meant for pulling out the required information from any text which is based on patterns. They are also widely used for manipulating the pattern-based texts which leads to text preprocessing and are very helpful in implementing digital skills like Natural Language Processing(NLP). This article demonstrates how to use re
7 min read
SpongeBob Mocking Text Generator - Python
SpongeBob mocking text (spongemock) is a style of writing in which the alphabets are randomly written in upper and lower case. It is used in internet communities to mock something. The text originated as a meme from the SpongeBob cartoon series.Examples : Input : The quick brown fox jumps over the lazy dog. Output : tHE QuiCK BrOWN fOX juMps over t
3 min read
Python program to count the number of blank spaces in a text file
All programs need input to process and after processing gives the output. Python support file handling and allow user to handle files. The concept of file handling has stretched over various other languages, But the implementation is either lengthy or complicated. Python treats file differently as text and binary,One thing to note while writing dat
3 min read
Sentiment Analysis of Hindi Text - Python
Sentiment Analysis for Indic Language: This article exhibits how to use the library VADER for doing the sentiment analysis of the Indic Language'Hindi'. Sentiment analysis is a metric that conveys how positive or negative or neutral the text or data is. It is performed on textual data to help businesses monitor brand and product sentiment in custom
3 min read
Classification of text documents using sparse features in Python Scikit Learn
Classification is a type of machine learning algorithm in which the model is trained, so as to categorize or label the given input based on the provided features for example classifying the input image as an image of a dog or a cat (binary classification) or to classify the provided picture of a living organism into one of the species from within t
5 min read
Disappearing Text Desktop Application in Python
In this article, we will build an exciting desktop application using Python and its GUI library, Tkinter. Disappearing Text Desktop Application in PythonThe app is simple to use. The user will start writing whatever he wants to write. If he takes a pause for 5 seconds, the text he has written is deleted. The user can even save his text in a text fi
12 min read
Get the Length of Text Without Using Inbuild Python Library Function
In Python, the length of a string can be calculated without using any library function by iterating through the characters of the string and counting them manually. This process involves creating a counter variable and incrementing it for each character encountered in the string. In this article, we will explore four different approaches to calcula
4 min read
three90RightbarBannerImg