Creating ChatBot Using Natural Language Processing in Python

Sonia Singla 13 Feb, 2024 • 8 min read

Introduction

Are you fed up with waiting in long queues to speak with a customer support representative? Can you recall the last time you interacted with customer service? There’s a chance you were contacted by a bot rather than a human customer support professional. In our blog post-ChatBot Building Using Python, we will discuss how to build a simple Chatbot in Python programming and its benefits.

Read on!

Python Chatbot

Learning Objectives

  1. Understanding Bots: Learn the meaning and types of bots, including chatbots, social media bots, Google bots, spam bots, transnational bots, and monitoring bots. Understand their significance in automating interactions and tasks on the internet.
  2. Rule-Based Chatbot Development: Explore the concept of rule-based chatbots that operate on predefined rules and patterns. Understand how to implement rule-based responses using Python, gaining insights into structured and specific task execution.
  3. Building a Simple ChatBot in Python: Learn step-by-step how to build a simple chatbot in Python. This includes user interaction, defining bot responses, creating functions for message processing, and breaking the loop for user termination. Gain hands-on experience with practical code examples.
  4. Introduction to Chatterbot and NLP: Discover the role of Natural Language Processing (NLP) in chatbot development. Explore the Chatterbot library in Python and understand how to install and use it to create chatbots. Also, gain knowledge of essential NLP libraries like NLTK and Spacy.

This article was published as a part of the Data Science Blogathon.

What is the meaning of Bots?

Bots are specially built software that interacts with internet users automatically. Bots are made up of deep learning and machine learning algorithms that assist them in completing jobs. By auto-designed, we mean they run independently, follow instructions, and begin the conservation process without human intervention. With their ability to mimic human languages seamlessly and engage in natural conversations, these smart bots have the power of self-learning and gain widespread adoption among companies in diverse industries.

Bots are responsible for the majority of internet traffic. For e-commerce sites, traffic can be significantly higher, accounting for up to 90% of total traffic. They can communicate with people on social media accounts and websites.

Some were programmed and manufactured to transmit spam messages to wreak havoc.

Also read: Python Tutorial for Beginners Overview

Type of Bots

Here are type of bots:

  1. Chatbot – An Artificial Intelligence (AI) programme that communicates with users through an app, message, or phone call. Twitter most commonly uses chatbots.
  2. Social Media Bot- Created for social media sites to answer automatically all at once.
  3. Google Bot is commonly used for indexing and crawling. Spider Bots—Developed for retrieving website data, the Google Bot is widely used for indexing and crawling. 
  4. Spam Bots – Spam Bots are programmed to send spam emails automatically to a list of addresses. 
  5. Transnational Bots – Transnational Bots are bots designed to be used in transactions. 
  6. Monitoring Bots – Creating bots to keep track of the system’s or website’s health. 

Rule-based chatbots operate on predefined rules and patterns, relying on instructions to respond to user inputs. These bots excel in structured and specific tasks, offering predictable interactions based on established rules.

Building libraries should be avoided if you want to understand how a chatbot operates in Python thoroughly. In 1994, Michael Mauldin was the first to coin the term “chatterbot” as Julia.

Also read: A Comprehensive Guide to Python Automation.

Simple ChatBot build by using Python

A ChatBot is essentially software that facilitates interaction between humans. When you train your chatbot with Python 3, extensive training data becomes crucial for enhancing its ability to respond effectively to user inputs.

ChatBot examples include Apple’s Siri, Amazon’s Alexa, Google Assistant, and Microsoft’s Cortana. Following is the step-by-step guide with regular expressions for building ChatBot using Python:

Interaction of User for asking the name

First, we will ask Username

print("BOT: What is your name?")
user_name = input()

Output

What is your name?
Testing

Response of ChatBot

To start, we assign questions and answers that the ChatBot must ask. For example, we assign three variables with different answers. It’s crucial to note that these variables can be used in code and automatically updated by simply changing their values. The format facilitates the easy passing of values.

name = "Bot Number 286" 
monsoon = "rainy" 
mood = "Smiley"
resp = { 
"what's your name?": [ 
"They call me {0}".format(name), 
"I usually go by {0}".format(name), 
"My name is the {0}".format(name) ],
"what's today's weather?": [ 
"The weather is {0}".format(monsoon), 
"It's {0} today".format(monsoon)], 
"how are you?": [ 
"I am feeling {0}".format(mood), 
"{0}! How about you?".format(mood), 
"I am {0}! How about yourself?".format(mood), ],
"": [ 
"Hey! Are you there?", 
"What do you mean by these?", 
 ],
"default": [
"This is a default message"] }
Python Chatbot

Creating a Function Response

Library random imported to choose the response. It will select the answer by bot randomly instead of the same act.

import random
def res(message):
if message in resp: 
        bot286_message = random.choice(resp[message])
else: 
        bot286_message = random.choice(resp["default"])
return bot286_message

Another Function

Sometimes, the questions added are not related to available questions, and sometimes, some letters are forgotten to write in the chat. The bot will not answer any questions then, but another function is forward.

def real(xtext): 
  if "name" in xtext: 
        ytext = "what's your name?"
elif "monsoon" in xtext: 
        ytext = "what's today's weather?"
elif "how are" in xtext: 
        ytext = "how are you?"
else: 
        ytext = ""
return ytext

Sending back the message function

def send_message(message): 
print((message)) 
response = res(message) 
print((response))

Final Step to break the loop

while 1: 
my_input = input() 
my_input = my_input.lower() 
related_text = real(my_input) 
send_message(related_text)
if my_input == "exit" or my_input == "stop": 
break

Another example is installing a library chatterbot

Chatterbot

Natural language Processing (NLP) is a necessary part of artificial intelligence that employs natural language to facilitate human-machine interaction.

Python uses many libraries such as NLTK, spacy, etc. A chatbot is a computer program that can communicate with humans in a natural language. They frequently rely on machine learning, particularly natural language processing (NLP).

Use the following commands in Terminal in Anaconda prompt.

pip install chatterbot
pip install chatterbot_corpus

You can also install chatterbot from its source: https://github.com/gunthercox/ChatterBot/archive/master.zip

After installing, unzip, the file and open Terminal, and type in:

cd chatter_bot_master_directory.

Finally, type python setup.py install.

For installing Spacy

pip install -U spacy

For downloading model “en_core_web_sm”

import spacy
from spacy.cli.download import download
download(model="en_core_web_sm")

or

pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz

Testing installation

import spacy
nlp = spacy.blank("en")
doc = nlp("This is a sentence.")

You will need two further classes ChatBot and ListTrainers

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

1st Example

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
# Create a new chatbot named Charlie
chatbot = ChatBot('name')
trainer = ListTrainer(chatbot)
trainer.train([
    "Hi, can I help you?",
    "Sure, I'd like to book a flight to Iceland.",
    "Your flight has been booked."
])
# Get a response to the input text 'I would like to book a flight.'
response = chatbot.get_response('I would like to book a flight.')
print(response)

2nd Example by ChatBot

Bot286 = ChatBot(name='PyBot')
talk = ['hi buddy!',
              'hi!',
              'how do you do?',
              'how are you?',
              'i'm fine.',
              'fine, you?',
              'always smiling.']
list_trainer = ListTrainer(Bot286)for item in (talk):
     list_trainer.train(item)
>>>print(my_bot.get_response("hi"))
 how do you do?
from chatterbot.trainers import ChatterBotCorpusTrainercorpus_trainer = ChatterBotCorpusTrainer(Bot286)
 corpus_trainer.train('chatterbot.corpus.english')

Benefits of Bots

Here are the benefits of Bots:

  1. Understandable information about the customer.
  2. It can be called a selling partner by making and sending the product information.
  3. They provide 24hrs services.
  4. Satisfy clients’ needs, as they will not continue waiting for your call. They need action quickly, or they will turn to another brand.
  5. Most customers prefer sending messages, texts, and SMS to the company for information. Marketing Bots can grow your business by increasing sales and satisfying needs. Facebook Messenger is one of the widely used messengers in the U.S.
  6. Recently, chatbots were used by the World Health Organization to provide information by ChatBot on WhatsApp.
  7. Facebook Messenger, Slack, Whatsapp, and Telegram make use of ChatBot.
  8. The modern need is there for Bot Building for the growth of Business to make progress.
  9. Another example of making use of ChatBo is Google Assistant and Siri.
  10. Bots, for the most part, operate on a network. Bots that can communicate with one another will use internet-based services like IRC.

Also read: Top 30+ Python Projects: Beginner to Advanced 2024

Conclusion

This article has delved into the fundamental definition of chatbots and underscored their pivotal role in business operations. By exploring the process of building your own chatbot using the Python programming language and the Chatterbot library, we’ve highlighted the critical aspects of handling text data, emphasizing the significance of preprocessing, such as tokenizing, for effective communication.

Moreover, including a practical use case with relevant parameters showcases the real-world application of chatbots, emphasizing their relevance and impact on enhancing user experiences. As businesses navigate the landscape of conversational AI, understanding the nuances of text data, mastering preprocessing techniques, and defining tailored use cases with specific parameters emerge as key considerations for successful chatbot integration.

Key Takeaways

  • Bots are autonomous software that uses deep learning and machine learning to interact with users. They are responsible for significant internet traffic, including spam, transnational, and monitoring bots.
  • Different types of bots include Chatbots, Social Media Bots, Google Bots for indexing, Spam Bots for automated spam emails, Transnational Bots for transactions, and Monitoring Bots for system health tracking.
  • Rule-based chatbots operate on predefined rules and patterns; excelling in structured tasks and avoiding building libraries is recommended for a deeper understanding of chatbot operations.
  • The article provides a step-by-step guide for building a simple chatbot in Python, emphasizing the importance of extensive training data for effective responses.
  • An alternative approach involves using the Chatterbot library for Natural Language Processing (NLP) in Python, with examples of installing and using Chatterbot along with NLTK and Spacy libraries.
  • Chatbots offer several advantages, including providing understandable information, acting as selling partners, offering 24/7 services, and satisfying client needs promptly. Examples include their use by the World Health Organization on WhatsApp and in popular messaging platforms like Facebook Messenger, Slack, Whatsapp, and Telegram.

Frequently Asked Questions (FAQs)

Q1. Can Python be used for a chatbot?

Ans. Yes, Python is commonly used for chatbots. Its versatility, extensive libraries like NLTK and spaCy for natural language processing, and frameworks like ChatterBot make it an excellent choice. Python’s simplicity, readability, and strong community support contribute to its popularity in developing effective and interactive chatbot applications.

Q2. What are the best Python libraries for creating a chatbot?

Ans. Popular Python libraries for chatbot development include NLTK, spaCy for natural language processing, TensorFlow, PyTorch for machine learning, and ChatterBot for simple implementations. Flask or Django can handle web integration. Rasa offers a comprehensive framework. Choose based on your project’s complexity, requirements, and library familiarity.

Q3. How do you make a Chatbot in Python using the Chatterbot Module?

Ans. To create a chatbot in Python using the ChatterBot module, install ChatterBot, create a ChatBot instance, train it with a dataset or pre-existing data, and interact using the chatbot’s logic. Implement conversation flow, handle user input, and integrate with your application. Deploy the chatbot for real-time interactions.

Q4. How do you make a generative AI chatbot in Python?

Ans. To craft a generative chatbot in Python, leverage a natural language processing library like NLTK or spaCy for text analysis. Utilize chatgpt or OpenAI GPT-3, a powerful language model, to implement a recurrent neural network (RNN) or transformer-based model using frameworks such as TensorFlow or PyTorch. Train the model on a dataset and integrate it into a chat interface for interactive responses.

Q5. How long does it take to make a chatbot in Python?

Ans. The time to create a chatbot in Python varies based on complexity and features. A simple one might take a few hours, while a sophisticated one could take weeks or months. It depends on the developer’s experience, the chosen framework, and the desired functionality and integration with other systems.

The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion.

Sonia Singla 13 Feb 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Ayush
Ayush 22 Jun, 2022

I want to made a chatbot can u plzz help me..

Related Courses

image.name
0 Hrs 21 Lessons
4.85

Introduction to Natural Language Processing

Free

NLP
Natural Language Processing
Become a full stack data scientist

  • [tta_listen_btn class="listen"]