Python - Remove Stopwords

Neha Kumawat

2 months ago

Stopwords are English words that don't add much meaning to a sentence. They can be safely ignored without detracting from the meaning of the sentence. For example, words like, he, have, etc. we record this in a corpus called corpus. First, we download it into our Python environment.

import nltk
nltk.download('stopwords')
A file with English stop words is being downloaded.

Verifying the Stopwords


from nltk.corpus import stopwords
stopwords.words('english')
print stopwords.words() [620:680]
If we run the above program, we get the following result:

[u'your', u'yours', u'yourself', u'yourselves', u'he', u'him', u'his', u'himself', u'she', 
u"she's", u'her', u'hers', u'herself', u'it', u"it's", u'its', u'itself', u'they', u'them', 
u'their', u'theirs', u'themselves', u'what', u'which', u'who', u'whom', u'this', 
u'that', u"that'll", u'these', u'those', u'am', u'is', u'are', u'was', u'were', u'be',
u'been', u'being', u'have', u'has', u'had', u'having', u'do', u'does', u'did', u'doing',
u'a', u'an', u'the', u'and', u'but', u'if', u'or', u'because', u'as', u'until',
u'while', u'of', u'at']
The various language other than English which has these stopwords are as below.


from nltk.corpus import stopwords
print stopwords.fileids()

If we run the above program, we get the following result:

[u'arabic', u'azerbaijani', u'danish', u'dutch', u'english', u'finnish', 
u'french', u'german', u'greek', u'hungarian', u'indonesian', u'italian', 
u'kazakh', u'nepali', u'norwegian', u'portuguese', u'romanian', u'russian',
u'spanish', u'swedish', u'turkish']

Example

We use the below example to show how the stopwords are removed from the list of words.

from nltk.corpus import stopwords
en_stops = set(stopwords.words('english'))

all_words = ['There', 'is', 'a', 'tree','near','the','river']
for word in all_words: 
    if word not in en_stops:
        print(word)
If we run the above program, we get the following result:

There
tree
near
river

Summary

Stopwords are English words that don't add much meaning to a sentence. They can be safely ignored without detracting from the meaning of the sentence. We record this in a corpus called corpus.
  
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at DeepVidhya.
Thanks for reading…
Happy Learning…  

Submit Review