Chatbot using the NLTK library | Build Chatbot in Python using NLTK

Contents

That's the beauty of a chatbot. A chatbot is AI-based software applied to NLP that deals with users to handle their specific queries without human interference..

39933chatbots20feature20img-8425875

Table of Contents

  • Brief about chatbots
  • What is the need for chatbots?
  • Types of chatbots
    • Rules-based chatbots
    • Self-learning chatbots
  • Chatbot using Python
  • Chatbot using Python and NLTK
  • Final notes

Brief introduction about Chatbot

A chatbot is a smart application that reduces human labor and helps an organization solve basic customer inquiries. Today, most companies, businesses from different sectors, they use the chatbot in a different way to respond to their customers as quickly as possible. Chatbots also help increase site traffic, which is the main business reason to use chatbots.

Chatbot requests basic information from customers, as the name, the email address and the query. If a query is simple, as product failure, reservation error, need information, then without any human connection it can solve it automatically and if any problem is high, pass the details to the human head and help the customer to connect with the manager of the organization easily. And most customers like to deal with and talk to a chatbot.

Why do we need Chatbots?

  • Cost and time effective ~ Humans cannot be active on the site. 24 hours of the day, the 7 weekdays, but chatbots can and the responsiveness of chatbots is much faster than humans.
  • Economic development cost ~ With the advancement of technology, many tools are developed that facilitate the development and integration of chatbots with little investment.
  • Human resources ~ Today, chatbots can also speak with text or voice technology, so it gives the feeling that a human is speaking from the other side.
  • Trademark ~ Businesses are changing with technology and the chatbot is one of them. Chatbot also helps in advertising, branding of the organization's products and services and provides daily updates to users.

Types of chatbots

There are mainly 2 types of chatbots.

1) Rules-based chatbots – As the name suggests, there are certain rules on which the chatbot operates. As a machine learning model, we train chatbots on user intentions and relevant responses, and based on these intentions, the chatbot identifies the intention and the response of the new user towards it.

2) Self-learning chatbots – Self-learning bots are very efficient because they are able to capture and identify user intent on their own. are built using advanced machine learning tools and techniques, deep learning and NLP. Self-learning bots are in turn divided into 2 subcategories.

  • Recovery-based chatbots: – Recovery-based is somewhat similar to rule-based, where predefined input patterns and responses are embedded.
  • Chatbots generativos: – It is based on the same phenomenon that machine translation is based on creating a sequence neural network 2 sequences.

Most of the organization uses a self-learning chatbot along with the incorporation of some rules as the hybrid version of both methods, what makes the chatbot powerful to handle every situation during a conversation with a customer.

Build one for yourself using Python

We now have an immense understanding of chatbot theory and its advancement in the future.. Let's get our hands dirty by building a simple rules-based chatbot using Python for ourselves.

We will design a simple GUI using the Python Tkinter module with which we will create a text box and a button to send the user's intention and, on the action, we will create a function in which we will match the user's intention and respond to them based on their intention. If you do not have the Tkinter module installed, first install it using the pip command.

pip install tkinter
from tkinter import *
root = Tk()
root.title("Chatbot")
def send():
    send = "You -> "+e.get()
    txt.insert(END, "n"+send)
    user = e.get().lower()
    if(user == "hello"):
        txt.insert(END, "n" + "Bot -> Hi")
    elif(user == "hi" or user == "this" or user == "hiiii"):
        txt.insert(END, "n" + "Bot -> Hello")
    elif(e.get() == "how are you"):
        txt.insert(END, "n" + "Bot -> fine! and you")
    elif(user == "fine" or user == "i am good" or user == "i am doing good"):
        txt.insert(END, "n" + "Bot -> Great! how can I help you.")
    else:
        txt.insert(END, "n" + "Bot -> Sorry! I dind't got you")
    e.delete(0, END)
txt = Text(root)
txt.grid(row=0, column=0, columnspan=2)
e = Entry(root, width=100)
e.grid(row=1, column=0)
send = Button(root, text="Send", command=send).grid(row=1, column=1)
root.mainloop()

Explanation – First we have created a blank window, thereafter, we create a text field using the input method and a button widget that when activating the calls, function send and, In return, get the response from the chatbot. We have used a basic If-else control statement to build a simple rule-based chatbot. And you can interact with the chatbot by running the application from the interface and you can see the result as shown below.

76583simple20chatbot-3621175

Chatbot implementation using the Python NLTK library

NLTK is the acronym for Natural Language Toolkit used to deal with NLP applications and the chatbot is one of them. We will now advance our rule-based chatbots using the NLTK library. Install the NLTK library first before working with the pip command.

pip install nltk

The first thing is to import the library and the classes that we need to use.

import nltk
from nltk.chat.util import Chat, reflections
  • Chat – The chat is a class that contains complete logic to process the text data that the chatbot receives and find useful information from it.
  • reflections – Another import that we have done is reflections, which is a dictionary containing the basic input and corresponding outputs. You can also create your own dictionary with more answers you want. if you print reflections it will be something like this.
reflections = {
  "i am"       : "you are",
  "i was"      : "you were",
  "i"          : "you",
  "i'm"        : "you are",
  "i'd"        : "you would",
  "i've"       : "you have",
  "i'll"       : "you will",
  "my"         : "your",
  "you are"    : "I am",
  "you were"   : "I was",
  "you've"     : "I have",
  "you'll"     : "I will",
  "your"       : "my",
  "yours"      : "mine",
  "you"        : "me",
  "me"         : "you"
}

let's start building the logic for the NLTK chatbot.

After importing the libraries, first we have to create rules. The lines of code shown below create a simple set of rules. the first line describes the user input that we have taken as raw string input and the next line is our chatbot response. You can modify these pairs according to the questions and answers you want.

pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, How are you today ?",]
    ],
    [
        r"hi|hey|hello",
        ["Hello", "Hey there",]
    ], 
    [
        r"what is your name ?",
        ["I am a bot created by DataPeaker. you can call me crazy!",]
    ],
    [
        r"how are you ?",
        ["I'm doing goodnHow about You ?",]
    ],
    [
        r"sorry (.*)",
        ["Its alright","Its OK, never mind",]
    ],
    [
        r"I am fine",
        ["Great to hear that, How can I help you?",]
    ],
    [
        r"i'm (.*) doing good",
        ["Nice to hear that","How can I help you?:)",]
    ],
    [
        r"(.*) age?",
        ["I'm a computer program dudenSeriously you are asking me this?",]
    ],
    [
        r"what (.*) want ?",
        ["Make me an offer I can't refuse",]
    ],
    [
        r"(.*) created ?",
        ["Raghav created me using Python's NLTK library ","top secret ;)",]
    ],
    [
        r"(.*) (location|city) ?",
        ['Indore, Madhya Pradesh',]
    ],
    [
        r"how is weather in (.*)?",
        ["Weather in %1 is awesome like always","Too hot man here in %1","Too cold man here in %1","Never even heard about %1"]
    ],
    [
        r"i work in (.*)?",
        ["%1 is an Amazing company, I have heard about it. But they are in huge loss these days.",]
    ],
    [
        r"(.*)raining in (.*)",
        ["No rain since last week here in %2","Damn its raining too much here in %2"]
    ],
    [
        r"how (.*) health(.*)",
        ["I'm a computer program, so I'm always healthy ",]
    ],
    [
        r"(.*) (sports|game) ?",
        ["I'm a very big fan of Football",]
    ],
    [
        r"who (.*) sportsperson ?",
        ["Messy","Ronaldo","Roony"]
    ],
    [
        r"who (.*) (moviestar|actor)?",
        ["Brad Pitt"]
    ],
    [
        r"i am looking for online guides and courses to learn data science, can you suggest?",
        ["Crazy_Tech has many great articles with each step explanation along with code, you can explore"]
    ],
    [
        r"quit",
        ["BBye take care. See you soon :) ","It was nice talking to you. See you soon :)"]
    ],
]

After creating rule pairs, we will define a function to start the chat process. The function is very simple, first greet the user and ask for help. And the conversation starts from here by calling a Chat class and passing them pairs and reflections.

def chat():
    print("Hi! I am a chatbot created by DataPeaker for your service")
    cat = Cat(pairs, reflections)
    chat.converse()
#initiate the conversation
if __name__ == "__main__":
    chat()

We have created an amazing rules-based chatbot just by using the Python library and NLTK. the nltk.chat works on various regex patterns present in user intent and, corresponding to her, present the output to a user. Let's run the app and chat with your created chatbot.

43199nltk_chatbot-1602273

Final notes

Chatbots are the leading natural language processing application and today it is easy to create and integrate with various websites and social media websites.. Today, most chatbots are created using tools like Dialogflow, FLAVOR, etc. This was a quick introduction to chatbots to present an understanding of how companies are transforming using data science and artificial intelligence..

Thank you for following the article to the end.. If you have any query, post it in the comment section below. If you like the article, also read my other articles through this link.

About the Author

Raghav Agrawal

I am pursuing my degree in computer science. I really like data science and big data. I love working with data and learning new technologies. Please, feel free to connect with me on Linkedin.

The media shown in this article is not the property of DataPeaker and is used at the author's discretion.

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.