AI Chatbot in Python (using NLTK): How to build a chatbot?

Spread the love

Have you wondered how a computer-based application solves your query in seconds when you contact a customer support executive? A map-based application in your mobile tells you which direction to reach your destination safely even when you are not aware of the routes? Who are they and how do they manage to get your query resolved? Well! a simple answer is ‘they are chatbots’ and in this article, we will talk about AI Chatbot in Python (using NLTK): How to build a chatbot? Follow these 8 simple steps on how to build your own Chatbot in Python.

Chatbot or chatterbot is becoming very popular nowadays due to their Instantaneous response, 24-hour service, and ease of communication.

In this article, we will learn about different types of chatbots, their advantages and disadvantages, and build a simple rule-based chatbot in Python (using NLTK) and Python Tkinter.

AI Chatbot in Python (using NLTK): How to build a chatbot?

The chatbot or chatterbot is a software application used to conduct an online chat conversation via text or text-to-speech, in lieu of providing direct contact with a live human agent.

The term “ChatterBot” was originally coined by Michael Mauldin (creator of the first Verbot) in 1994 to describe these conversational programs.

Today almost all industries use chatbots for providing a good customer service experience. In one of the reports published by Gartner, “ By 2022, 70% of white-collar workers will interact with conversational platforms on a daily basis”.

Chatbot in Python: Types of Chatbot

The chatbot is broadly classified into two types-

  1. Text-based chatbots for example Customer Support Assitant
  2. Voice-based or speech-based chatbots for example Google Home, Alexa, Apple Siri, Cortana

In this article, we will focus on text-based chatbots with the help of an example.

The text-based chatbots are further classified into two types-

  1. Rule-based
  2. Self-learn or AI (Artificial Intelligence) based


In Rule-based chatbots, the bot answers the queries based on some pre-defined rules on which it is trained.


  1. Rule-based chatbots are easy or faster to train
  2. Accountable, Secure, and not restricted to the text interactions


  1. It is not capable of handling complex queries
  2. Interactions are not conversational
  3. It requires a lot of manual work to generate or prepare rules for training the chatbots

Self-learn or AI-based

In a Self-learn or AI-based chatbots, the bots are machine learning-based programs that simulate human-like conversations using natural language processing (NLP).


  1. Increase customer engagement by providing interactions conversational
  2. Increase productivity by providing quick data collection and better lead generation


  1. It difficult to train as it requires high computational power for example GPU, and RAM
  2. The cost of installation is high as compared to rule-based chatbots

Industries using AI chatbot

According to an article published in, top industries using chatbots are as follows-

  1. Healthcare
  2. Telecommunications
  3. Banking
  4. Financial Advice
  5. Insurance
  6. Government
Building a Chatbot in Python
Building a Chatbot

Building a Semi-Rule Based AI Chatbot in Python

The first and foremost thing before starting to build a chatbot is to understand the architecture. For example, how chatbots communicate with the users and model to provide an optimized output.

Chatbot Architecture
Chatbot Architecture

In the above image, we have Training Data/ Corpus, Application DB, NLP Model, and a Chat Session.

Training Data/ Corpus

In any machine learning model, we need a dataset using which we can train the model to predict the desired output. For example, to predict future sales we need historical data which can be used to fit the model.

In our case, the corpus or training data are a set of rules with various conversations of human interactions.

Corpus can be created or designed either manually or by using the accumulated data over time through the chatbot.

Chatbot Corpus/ Training Data
Chatbot Corpus/ Training Data

The above image shows the structure of a corpus that includes intents, tags, patterns, responses, and context.

Application DB

Application DB is used to process the actions performed by the chatbot.

NLP Model

The NLP model is a Deep-Learning model. As per SAS, Natural language processing helps computers communicate with humans in their own language and scales other language-related tasks. For example, NLP makes it possible for computers to read text, hear speech, interpret it, measure sentiment, and determine which parts are important.

Chat Session/ User Interface

A chat session or User Interface is a frontend application used to interact between the chatbot and end-user.

Read More Articles

1- Download Any Ebook For Free

2- Free Data Science Courses For Beginners

3- How To Build Email Spam Classification?

4- Deploying Your Python Flask Application Online: Using Ngrok

Coding a Chatbot in Python

Let’s have a look at How to make a chatbot in python? We will divide the Jupyter Notebook into the followings steps

  1. Importing necessary libraries
  2. Data pre-processing
  3. Creating training data
  4. Creating a neural network model
  5. Create functions to take user input, pre-process the input, predict the class, and get the response
  6. Start the chatbot using command line option
  7. Build the GUI using Python’s Tkinter library
  8. Start the chatbot using Tkinter GUI

Step 1. Importing necessary libraries

Chatbot- Importing Necessary Libraries
Chatbot- Importing Necessary Libraries

In the above image, we have imported all the necessary libraries. We will discuss most of it in later steps. In the first step only we have to import the JSON data which contains rules using which we have to train our NLP model. We have also created empty lists for words, classes, and documents.

Step 2. Data pre-processing

Data preprocessing can refer to the manipulation or dropping of data before it is used in order to ensure or enhance performance, and is an important step in the data mining process. It takes the maximum time of any model building exercise which is almost 70%.

Chatbot- Corpus Pre-processing
Chatbot- Corpus Pre-processing

In the above image, we are using the Corpus Data which contains nested JSON values, and updating the existing empty lists words, documents, and classes.

Tokenize or Tokenization is used to split a large sample of text or sentences into words. In the below image, I have shown the sample from each list we have created.

Chatbot- Corpus Lists Sample
Chatbot- Corpus Lists Sample
Chatbot- Lemmatizer
Chatbot- Lemmatizer

In the above output, we have observed a total of 128 documents, 8 classes, and 158 unique lemmatized words. We have also saved the words and classes for our future use.


Lemmatization is the grouping together the inflected forms of words into one word. For example, the root word or lemmatized word for trouble, troubling, troubled, and troubles is trouble. Using the same concept, we have a total of 128 unique root words present in our training dataset.

Step 3. Creating training data

Chatbot- Training Data
Chatbot- Training Data

In the above image, we have created a bow (bag of words) for each sentence. Basically, a bag of words is a simple representation of each text in a sentence as the bag of its words.

For example, consider the following sentence “John likes to watch movies. Mary likes movies too”.

Bag of Words- Example
Bag of Words- Example

After creating the training dataset, we have to shuffle the data and convert the lists into NumPy array so that we can use it in our model.

Now, separate the features and target column from the training data as specified in the above image.

Step 4. Creating a neural network model

In this step, we will create a simple sequential NN model using one input layer (input shape will be the length of the document), one hidden layer, an output layer, and two dropout layers.

Chatbot- NLP Model or Neural Network Model
Chatbot- NLP Model

The summary of the model is shown in the below image.

Chatbot- NN Model Summary
Chatbot- NN Model Summary

The accuracy of the above Neural Network model is almost 100% which is quite impressive. Also, we have saved the model for future use.

Interested in learning Python, read ‘Python API Requests- A Beginners Guide On API Python 2022‘.

Step 5. Create functions to take user input, pre-process the input, predict the class, and get the response

Function to clean the sentence or user input
Chatbot- Clean Sentence
Chatbot- Clean Sentence
Function to create bow (bag of words) using the clean sentence from the above step
Chatbot- Bag of words
Chatbot- Bag of words
Function to predict the target class
Chatbot- Predict Class
Chatbot- Predict Class
Function to get the response from the model
Chatbot- Get Response
Chatbot- Get Response
Function to start the chatbot which will run till the user type ‘end’
Chatbot- Start Service
Chatbot- Start Service

Step 6. Start the chatbot using the command line option

In the last step, we have created a function called ‘start_chat’ which will be used to start the chatbot. Refer to the below image.


The message box will be used to pass the user input. The complete chat is shown below.

Chatbot- Complete Chat
Chatbot- Complete Chat

Step 7. Build the GUI using Python’s Tkinter library

Python’s Tkinter is a library in Python which is used to create a GUI-based application. It is a standard GUI library for python.

How to create a Tkinter App in Python is out of the scope of this article but you can refer to the official documentation for more information.

In the below image I have used the Tkinter in python to create a GUI. Please note that if you are using Google Colab then Tkinter will not work. You have to use your local system/PC to use the Tkinter library.

Chatbot- Tkinter GUI
Chatbot- Tkinter GUI

In the above, we have created two functions, “greet_res()” to greet the user based on bot_greet and usr_greet lists and “send_msz()” to send the message to the user.

Step 8. Start the chatbot using Tkinter GUI

Chatbot- Tkinter GUI/ Python Tkinter App
Chatbot- Tkinter GUI

Congratulations! We have successfully created a chatbot that can respond based on user input.

In the above example, we have successfully created a simple yet powerful semi-rule-based chatbot.

Complete Jupyter Notebook File- How to create a Chatbot using Natural Language Processing Model and Python Tkinter GUI Library.

Github Repository

Chatbot- NLP Github Repository

Here is another example of Chatbot Using Python Project in which we have have to determine the Potential Level of Accident Based on the accident description provided by the user. We have build a customized web-based UI. Also, created API using the Python Flask for sending the request to predict the output.

Python Chatbot Example- Chatbot in python
Python Chatbot Example

Learning Resource

Learning Resource

If you want to learn How to create a Chatbot in Python? then you can join this free course Offered by Great Learning. You will get a free course completion certificate which you can share with your network for example Linkedin or any social network and even write in your resume. Further, if you want to explore more about Data Science and build your career as an Analytics Professional, then you can these free courses offered by top institutes and universities from all over the world.

Further, If you want to explore “How we can deploy this Chatbot using Python Flask?” You can refer to my article on How to Run Python Flask App Online using Ngrok?

If you want to learn more about Chatbot, you can download free ebooks using these simple tricks explained here.


In this article, we have successfully discussed Chatbots and their types and created a semi-rule-based chatbot by cleaning the Corpus data, pre-processing, and training the Sequential NN model. We have discussed tokenization, bag of words, lemmatization, and also created a Python Tkinter-based GUI for our chatbot.

Please support our effort by commenting below. Feel free to contact us in case of any queries.

Interested in making money online? Read this article on How To Make Money Online 2022: A Beginner’s Guide On NFT

Spread the love

Related Posts

This Post Has 13 Comments

  1. With chatbot for business, there is no limitation to what you
    can achieve. From Restaurant Reservations to receiving Ecommerce payments by sending
    relevant products to users, we can do it all.
    Not just that, Integrating your chatbot with 3rd party
    apis and databases will allow bots to perform tasks otherwise not possible with
    simple messages.

  2. I have been browsing online more than 2 hours today, yet I never found any interesting
    article like yours. It’s pretty worth enough for me.
    In my opinion, if all site owners and bloggers made good content as you did,
    the internet will be a lot more useful than ever before.

  3. Fantastic beat ! I would like to apprentice while you amend your website, how can i subscribe for a blog web site?
    The account aided me a acceptable deal. I had been tiny
    bit acquainted of this your broadcast provided bright
    clear concept

  4. Hello, yeah this post is truly pleasant and I have learned lot of things
    from it regarding blogging. thanks.

  5. Hello There. I found your blog using msn. That
    is an extremely well written article. I’ll be sure to bookmark it and come back to read more of your useful info.
    Thank you for the post. I will definitely comeback.

Leave a Reply

Your email address will not be published.

© 2022 Pykit - All Rights Reserved!