Introduction to Word Frequency in NLP using python

Milind Soorya / September 12, 2021

4 min read

redis crash course banner


Natural Language Processing is one of the most commonly used techniques which is implemented in machine learning applications — given the wide range of analysis, extraction, processing and visualizing tasks that it can perform. The primary goal of this exercise is to tokenize the textual content, remove the stop words, and find the high-frequency words. we will be using NLTk, a popular NLP package in python for finding the frequency of words in some given text sample.

The libraries that we are going to use:

  • Beautifulsoup: To scrape the data from the HTML of a website and it also helps to process only the text from these HTML codes
  • Regular Expressions: Also known as Regex. It will convert the noise data containing special characters and carry the conversion of uppercase to lowercase characters
  • NLTK (Natural Language Toolkit): For the tokenization of the sentences into a list of words

In the end, we will look at how the graph looks and also the tokenized word count.

Data processing

  1. Import the libraries needed
  2. Load the data from the link
  3. Extract the data from HTML
  4. Convert text to tokens

Using NLP

  1. Remove stop words from the text
  2. Get a list of all words after removing stop words
  3. Analysing word frequency and plot the graph

Environment setup

I used anaconda to setup a python virtual enviroment in conda. You can read how to set it up in this article

Using a Jupyter Notebook is the recommended approch to run the following exercise. Jupyter notebook comes preinstalled with anaconda and you can run it by the command jupyter notebook from your anaconda prompt.

Import the needed libraries

#import the required packages
import requests
from bs4 import BeautifulSoup
import re
import nltk
import seaborn as sns
import matplotlib.pyplot as plt
#get the dataset from link

Extract text from HTML

# extract the text using web scraping tool
<title>The Project Gutenberg Book of The Adventures of Sherlock Holmes, by Arthur Conan Doyle</title>
# [:12] gives the first 12 elements in the matched array
[<a href=""></a>,
<a href="">
[ #48320 ]</a>,
<a href="#chap01">A Scandal in Bohemia</a>,
<a href="#chap02">The Red-Headed League</a>,
<a href="#chap03">A Case of Identity</a>,
<a href="#chap04">The Boscombe Valley Mystery</a>,
<a href="#chap05">The Five Orange Pips</a>,
<a href="#chap06">The Man with the Twisted Lip</a>,
<a href="#chap07">The Adventure of the Blue Carbuncle</a>,
<a href="#chap08">The Adventure of the Speckled Band</a>,
<a href="#chap09">The Adventure of the Engineer’s Thumb</a>,
<a href="#chap10">The Adventure of the Noble Bachelor</a>]

Convert text into tokens

# tokenize the text with regular expressions
# "w+": This expression matches the alphanumeric character in the text
token=re.findall('\w+', text)
for word in token:
['the', 'project', 'gutenberg', 'book', 'of', 'the', 'adventures', 'of']

Remove all the stopwords

# download the package"stopwords")
[nltk_data] Downloading package stopwords to
[nltk_data] C:\Users\milind\AppData\Roaming\nltk_data...
[nltk_data] Package stopwords is already up-to-date!
# remove stop words
['i', 'me', 'my', 'myself', 'we']

Get a list of words without stop words

# get the list without stop words
for word in words:
if word not in sw:
['project', 'gutenberg', 'book', 'adventures', 'sherlock']

Plot the word frequency

word frequency output


Word frequency identification is one of the initial step in spam detection classifier and a basic understanding of NLTK and beautifulsoup is essential.

Next step

As you have successfully completed word frequency, now build a spam classifier using this knowledge

👉 Build a Spam Classifier using python

You might also like

Learn about building products as a Data Scientist

Get a once-per-month email with my latest article and additional details about my launches, products, and experiments ✨

No spam, sales, or ads. Unsubscribe as your heart desires.