The Wayback Machine - https://web.archive.org/web/20240927031115/https://www.geeksforgeeks.org/removing-stop-words-nltk-python/
Open In App

Removing stop words with NLTK in Python

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

In natural language processing (NLP), stopwords are frequently filtered out to enhance text analysis and computational efficiency. Eliminating stopwords can improve the accuracy and relevance of NLP tasks by drawing attention to the more important words, or content words. The article aims to explore stopwords.

Certain words, like “the,” “and,” and “is,” are thought to be ineffective for communicating important information. The objective of eliminating words that add little or nothing to the comprehension of the text is to expedite text processing, even though the list of stopwords may differ.

What are Stop words?

A stop word is a commonly used word (such as “the”, “a”, “an”, or “in”) that a search engine has been programmed to ignore, both when indexing entries for searching and when retrieving them as the result of a search query. 

We would not want these words to take up space in our database or take up valuable processing time. For this, we can remove them easily, by storing a list of words that you consider to stop words. NLTK(Natural Language Toolkit) in Python has a list of stopwords stored in 16 different languages. You can find them in the nltk_data directory. home/PratimaPython/nltk_data/corpora/stopwords are the directory address. or (Do not forget to change your home directory name)

Stop word removal using NLTK

Need to remove the Stopwords

The necessity of removing stopwords in NLP is contingent upon the specific task at hand. For text classification tasks, where the objective is to categorize text into distinct groups, excluding stopwords is common practice. This is done to channel more attention towards words that truly convey the essence of the text. As illustrated earlier, certain words like “there,” “book,” and “table” contribute significantly to the text’s meaning, unlike less informative words such as “is” and “on.”

Conversely, for tasks like machine translation and text summarization, the removal of stopwords is not recommended. In these scenarios, every word plays a pivotal role in preserving the original meaning of the content.

Types of Stopwords

Stopwords are frequently occurring words in a language that are frequently omitted from natural language processing (NLP) tasks due to their low significance for deciphering textual meaning. The particular list of stopwords can change based on the language being studied and the context. The following is a broad list of stopword categories:

  • Common Stopwords: These are the most frequently occurring words in a language and are often removed during text preprocessing. Examples include “the,” “is,” “in,” “for,” “where,” “when,” “to,” “at,” etc.
  • Custom Stopwords: Depending on the specific task or domain, additional words may be considered as stopwords. These could be domain-specific terms that don’t contribute much to the overall meaning. For example, in a medical context, words like “patient” or “treatment” might be considered as custom stopwords.
  • Numerical Stopwords: Numbers and numeric characters may be treated as stopwords in certain cases, especially when the analysis is focused on the meaning of the text rather than specific numerical values.
  • Single-Character Stopwords: Single characters, such as “a,” “I,” “s,” or “x,” may be considered stopwords, particularly in cases where they don’t convey much meaning on their own.
  • Contextual Stopwords: Words that are stopwords in one context but meaningful in another may be considered as contextual stopwords. For instance, the word “will” might be a stopword in the context of general language processing but could be important in predicting future events.

Checking English Stopwords List

An English stopwords list typically includes common words that carry little semantic meaning and are often excluded during text analysis. Examples of these words are “the,” “and,” “is,” “in,” “for,” and “it.” These stopwords are frequently removed to focus on more meaningful terms when processing text data in natural language processing tasks such as text classification or sentiment analysis.

To check the list of stopwords you can type the following commands in the python shell. 

Python3




import nltk
from nltk.corpus import stopwords
 
nltk.download('stopwords')
print(stopwords.words('english'))


Output:

['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 
'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself',
'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself',
'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves',
'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are',
'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing',
'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for',
'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to',
'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once',
'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very',
's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y',
'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't",
'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn',
"mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't",
'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

Note: You can even modify the list by adding words of your choice in the English .txt. file in the stopwords directory. 

Removing stop words with NLTK

The following program removes stop words from a piece of text:  

Python3




from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
 
example_sent = """This is a sample sentence,
                  showing off the stop words filtration."""
 
stop_words = set(stopwords.words('english'))
 
word_tokens = word_tokenize(example_sent)
# converts the words in word_tokens to lower case and then checks whether
#they are present in stop_words or not
filtered_sentence = [w for w in word_tokens if not w.lower() in stop_words]
#with no lower case conversion
filtered_sentence = []
 
for w in word_tokens:
    if w not in stop_words:
        filtered_sentence.append(w)
 
print(word_tokens)
print(filtered_sentence)


Output:

['This', 'is', 'a', 'sample', 'sentence', ',', 'showing', 
'off', 'the', 'stop', 'words', 'filtration', '.']
['This', 'sample', 'sentence', ',', 'showing', 'stop',
'words', 'filtration', '.']

The provided Python code demonstrates stopword removal using the Natural Language Toolkit (NLTK) library. In the first step, the sample sentence, which reads “This is a sample sentence, showing off the stop words filtration,” is tokenized into words using the word_tokenize function. The code then filters out stopwords by converting each word to lowercase and checking its presence in the set of English stopwords obtained from NLTK. The resulting filtered_sentence is printed, showcasing both lowercased and original versions, providing a cleaned version of the sentence with common English stopwords removed.

Removing stop words with SpaCy

Python3




import spacy
 
# Load spaCy English model
nlp = spacy.load("en_core_web_sm")
 
# Sample text
text = "There is a pen on the table"
 
# Process the text using spaCy
doc = nlp(text)
 
# Remove stopwords
filtered_words = [token.text for token in doc if not token.is_stop]
 
# Join the filtered words to form a clean text
clean_text = ' '.join(filtered_words)
 
print("Original Text:", text)
print("Text after Stopword Removal:", clean_text)


Output:

Original Text: There is a pen on the table
Text after Stopword Removal: pen table

The provided Python code utilizes the spaCy library for natural language processing to remove stopwords from a sample text. Initially, the spaCy English model is loaded, and the sample text, “There is a pen on the table,” is processed using spaCy. Stopwords are then filtered out from the processed tokens, and the resulting non-stopword tokens are joined to create a clean version of the text.

Removing stop words with Genism

Python3




from gensim.parsing.preprocessing import remove_stopwords
 
# Another sample text
new_text = "The majestic mountains provide a breathtaking view."
 
# Remove stopwords using Gensim
new_filtered_text = remove_stopwords(new_text)
 
print("Original Text:", new_text)
print("Text after Stopword Removal:", new_filtered_text)


Output:

Original Text: The majestic mountains provide a breathtaking view.
Text after Stopword Removal: The majestic mountains provide breathtaking view.

The provided Python code utilizes Gensim’s remove_stopwords function to preprocess a sample text. In this specific example, the original text is “The majestic mountains provide a breathtaking view.” The remove_stopwords function efficiently eliminates common English stopwords, resulting in a filtered version of the text, which is then printed alongside the original text.

Removing stop words with SkLearn

Python3




from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
 
# Another sample text
new_text = "The quick brown fox jumps over the lazy dog."
 
# Tokenize the new text using NLTK
new_words = word_tokenize(new_text)
 
# Remove stopwords using NLTK
new_filtered_words = [
    word for word in new_words if word.lower() not in stopwords.words('english')]
 
# Join the filtered words to form a clean text
new_clean_text = ' '.join(new_filtered_words)
 
print("Original Text:", new_text)
print("Text after Stopword Removal:", new_clean_text)


Output:

Original Text: The quick brown fox jumps over the lazy dog.
Text after Stopword Removal: quick brown fox jumps lazy dog .

The provided Python code combines scikit-learn and NLTK for stopword removal and text processing. First, the sample text, “The quick brown fox jumps over the lazy dog,” is tokenized into words using NLTK’s word_tokenize function. Subsequently, common English stopwords are removed by iterating through the tokenized words and checking their absence in the NLTK stopwords set. The final step involves joining the non-stopword tokens to create a clean version of the text. This approach integrates scikit-learn’s CountVectorizer could be utilized for further text analysis, such as creating a bag-of-words representation.

Also Check:

Frequently Asked Questions

1. What are stopwords in NLP?

Stopwords are common words in a language that are often filtered out during NLP tasks because they are considered to carry little meaning or contribute minimally to the overall understanding of a text. Examples include “the,” “is,” “and,” “in,” etc.

2. Why do we remove stopwords in NLP?

Stopwords are removed in NLP to focus on the more meaningful and informative words in a text. This is often done to reduce noise, improve efficiency in processing, and highlight keywords that carry the essential meaning of the text.

3. Can the list of stopwords vary between NLP libraries?

Yes, the list of stopwords can vary between NLP libraries. Different libraries, such as NLTK, spaCy, Gensim, and scikit-learn, may provide their own sets of stopwords. Users can also customize the list based on their specific needs.

4. When should stopwords be retained?

Stopwords should be retained when they contribute to the context, coherence, or specific linguistic features of the text. Tasks like machine translation, text summarization, and certain sentiment analysis scenarios may benefit from retaining stopwords.

5. What are some common English stopwords?

Common English stopwords include “the,” “and,” “is,” “in,” “for,” “where,” “when,” “to,” “at,” etc. These words are frequently used but are often excluded during text analysis.



Similar Reads

Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
Python NLTK | nltk.tokenize.TabTokenizer()
With the help of nltk.tokenize.TabTokenizer() method, we are able to extract the tokens from string of words on the basis of tabs between them by using tokenize.TabTokenizer() method. Syntax : tokenize.TabTokenizer() Return : Return the tokens of words. Example #1 : In this example we can see that by using tokenize.TabTokenizer() method, we are abl
1 min read
Python NLTK | nltk.tokenize.SpaceTokenizer()
With the help of nltk.tokenize.SpaceTokenizer() method, we are able to extract the tokens from string of words on the basis of space between them by using tokenize.SpaceTokenizer() method. Syntax : tokenize.SpaceTokenizer() Return : Return the tokens of words. Example #1 : In this example we can see that by using tokenize.SpaceTokenizer() method, w
1 min read
Python NLTK | nltk.tokenize.StanfordTokenizer()
With the help of nltk.tokenize.StanfordTokenizer() method, we are able to extract the tokens from string of characters or numbers by using tokenize.StanfordTokenizer() method. It follows stanford standard for generating tokens. Syntax : tokenize.StanfordTokenizer() Return : Return the tokens from a string of characters or numbers. Example #1 : In t
1 min read
Python NLTK | nltk.tokenizer.word_tokenize()
With the help of nltk.tokenize.word_tokenize() method, we are able to extract the tokens from string of characters by using tokenize.word_tokenize() method. It actually returns the syllables from a single word. A single word can contain one or two syllables. Syntax : tokenize.word_tokenize() Return : Return the list of syllables of words. Example #
1 min read
Python NLTK | nltk.tokenize.mwe()
With the help of NLTK nltk.tokenize.mwe() method, we can tokenize the audio stream into multi_word expression token which helps to bind the tokens with underscore by using nltk.tokenize.mwe() method. Remember it is case sensitive. Syntax : MWETokenizer.tokenize() Return : Return bind tokens as one if declared before. Example #1 : In this example we
1 min read
Python NLTK | nltk.WhitespaceTokenizer
With the help of nltk.tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from string of words or sentences without whitespaces, new line and tabs by using tokenize.WhitespaceTokenizer() method. Syntax : tokenize.WhitespaceTokenizer() Return : Return the tokens from a string Example #1 : In this example we can see that by using
1 min read
Python NLTK | nltk.tokenize.LineTokenizer
With the help of nltk.tokenize.LineTokenizer() method, we are able to extract the tokens from string of sentences in the form of single line by using tokenize.LineTokenizer() method. Syntax : tokenize.LineTokenizer() Return : Return the tokens of line from stream of sentences. Example #1 : In this example we can see that by using tokenize.LineToken
1 min read
Python NLTK | nltk.tokenize.SExprTokenizer()
With the help of nltk.tokenize.SExprTokenizer() method, we are able to extract the tokens from string of characters or numbers by using tokenize.SExprTokenizer() method. It actually looking for proper brackets to make tokens. Syntax : tokenize.SExprTokenizer() Return : Return the tokens from a string of characters or numbers. Example #1 : In this e
1 min read
Python | NLTK nltk.tokenize.ConditionalFreqDist()
With the help of nltk.tokenize.ConditionalFreqDist() method, we are able to count the frequency of words in a sentence by using tokenize.ConditionalFreqDist() method. Syntax : tokenize.ConditionalFreqDist() Return : Return the frequency distribution of words in a dictionary. Example #1 : In this example we can see that by using tokenize.Conditional
1 min read
Python NLTK | nltk.TweetTokenizer()
With the help of NLTK nltk.TweetTokenizer() method, we are able to convert the stream of words into small tokens so that we can analyse the audio stream with the help of nltk.TweetTokenizer() method. Syntax : nltk.TweetTokenizer() Return : Return the stream of token Example #1 : In this example when we pass audio stream in the form of string it wil
1 min read
Correcting Words using NLTK in Python
nltk stands for Natural Language Toolkit and is a powerful suite consisting of libraries and programs that can be used for statistical natural language processing. The libraries can implement tokenization, classification, parsing, stemming, tagging, semantic reasoning, etc. This toolkit can make machines understand human language. We are going to u
4 min read
Python NLTK | tokenize.regexp()
With the help of NLTK tokenize.regexp() module, we are able to extract the tokens from string by using regular expression with RegexpTokenizer() method. Syntax : tokenize.RegexpTokenizer() Return : Return array of tokens using regular expression Example #1 : In this example we are using RegexpTokenizer() method to extract the stream of tokens with
1 min read
Python NLTK | tokenize.WordPunctTokenizer()
With the help of nltk.tokenize.WordPunctTokenizer()() method, we are able to extract the tokens from string of words or sentences in the form of Alphabetic and Non-Alphabetic character by using tokenize.WordPunctTokenizer()() method. Syntax : tokenize.WordPunctTokenizer()() Return : Return the tokens from a string of alphabetic or non-alphabetic ch
1 min read
Python | Lemmatization with NLTK
Lemmatization is a fundamental text pre-processing technique widely applied in natural language processing (NLP) and machine learning. Serving a purpose akin to stemming, lemmatization seeks to distill words to their foundational forms. In this linguistic refinement, the resultant base word is referred to as a "lemma." The article aims to explore t
6 min read
How To Remove Nltk From Python
In Python, NLTK, or Natural Language Toolkit, is a powerful library that is used for human language data. This library provides tools for tasks like tokenization, stemming, tagging, passing, and more. Once the usage of the library is done, we can remove NLTK from our system. So we can remove it using the pip package manager. In this article, we wil
1 min read
Tokenize text using NLTK in python
To run the below python program, (NLTK) natural language toolkit has to be installed in your system.The NLTK module is a massive tool kit, aimed at helping you with the entire Natural Language Processing (NLP) methodology.In order to install NLTK run the following commands in your terminal. sudo pip install nltkThen, enter the python shell in your
3 min read
Python concordance command in NLTK
The Natural Language Toolkit (NLTK) is a powerful library in Python for working with human language data (text). One of its many useful features is the concordance command, which helps in text analysis by locating occurrences of a specified word within a body of text and displaying them along with their surrounding context. This can be particularly
7 min read
How to use CoreNLPParser in NLTK in Python
The Stanford CoreNLP toolkit, integrated with the Natural Language Toolkit (NLTK) in Python, provides robust tools for linguistic analysis. One of the powerful components of this integration is the CoreNLPParser, which allows for advanced parsing and linguistic analysis of text. In this article, we are going to discuss how to leverage CoreNLPParser
7 min read
How to remove punctuations in NLTK
Natural Language Processing (NLP) involves the manipulation and analysis of natural language text by machines. One essential step in preprocessing text data for NLP tasks is removing punctuations. In this article, we will explore how to remove punctuations using the Natural Language Toolkit (NLTK), a popular Python library for NLP. Need for Punctua
4 min read
Generate bigrams with NLTK
Bigrams, or pairs of consecutive words, are an essential concept in natural language processing (NLP) and computational linguistics. Their utility spans various applications, from enhancing machine learning models to improving language understanding in AI systems. In this article, we are going to learn how bigrams are generated using NLTK library.
5 min read
Accessing Text Corpora and Lexical Resources using NLTK
Accessing Text Corpora and Lexical Resources using NLTK provides efficient access to extensive text data and linguistic resources, empowering researchers and developers in natural language processing tasks. Natural Language Toolkit (NLTK) is a powerful Python library for natural language processing (NLP). It provides easy-to-use interfaces to over
5 min read
Creating a New Corpus with NLTK
The Natural Language Toolkit (NLTK) is a robust and versatile library for working with human language data in Python. Whether you're involved in research, data analysis, or developing applications, creating your own corpus can be incredibly useful for specific projects. This article will guide you through the process of creating a new corpus with N
5 min read
N-Gram Language Modelling with NLTK
Language modeling is the way of determining the probability of any sequence of words. Language modeling is used in various applications such as Speech Recognition, Spam filtering, etc. Language modeling is the key aim behind implementing many state-of-the-art Natural Language Processing models. Methods of Language ModellingTwo methods of Language M
5 min read
Stop Word Removal In R
In Natural Language Processing, different words carry different amounts of information. We want to select only those words which are meaningful to the machine learning models. By analyzing the text, some words are often found repetitive and do not carry much information. Instead, they degrade the model performance by introducing unnecessary bias. T
9 min read
In Which Epoch Should I Stop the Training to Avoid Overfitting?
Answer: You should stop the training when the validation loss starts to increase, indicating the onset of overfitting.Determining the optimal epoch to stop training and avoid overfitting depends on monitoring the model's performance on a validation dataset. Here's a detailed explanation: Validation Loss: During training, it's common to split the da
2 min read
Python - Removing Constant Features From the Dataset
Those features which contain constant values (i.e. only one value for all the outputs or target values) in the dataset are known as Constant Features. These features don't provide any information to the target feature. These are redundant data available in the dataset. Presence of this feature has no effect on the target, so it is good to remove th
2 min read
Removing the Toolbar from a Chart in Python Bokeh
Bokeh is a powerful Python library for interactive data visualization. One of its notable features is the ability to customize plots extensively, including the appearance and functionality of toolbars. In this article, we’ll explore how to remove the toolbar from a Bokeh chart. This can be useful when you want to simplify the user interface or focu
4 min read
Removing the Color Bar in Seaborn Heatmaps
Seaborn is a powerful Python visualization library based on Matplotlib that provides a high-level interface for drawing attractive and informative statistical graphics. One of the most commonly used plots in Seaborn is the heatmap, which is used to visualize matrix-like data. By default, Seaborn adds a color bar to the heatmap to indicate the mappi
5 min read
Removing Palette Colors from Heatmaps
Heatmaps are a powerful visualization tool used to represent complex data in a concise and intuitive manner. One of the key elements that contribute to the effectiveness of heatmaps is the color palette. However, there may be situations where you want to remove or modify the palette colors to better suit your needs. This article will delve into the
4 min read