How to create a chatbot in Python

by | Jun 27, 2019 | Tutorials

Natural language processing (NLP) is one of the most promising fields of artificial intelligence that uses natural languages to enable human interactions with machines.
There are two main approaches to NLP:
– rule-based methods,
– statistical methods, i.e., methods related to machine learning.

There are several exciting Python libraries for NLP, such as Natural Language Toolkit (NLTK), spaCy, TextBlob, etc.

A chatbot is a computer software able to interact with humans using a natural language. They usually rely on machine learning, especially on NLP. Apple’s Siri, Amazon’s Alexa, Google Assitant, and Microsoft’s Cortana are some well-known examples of software able to process natural languages.

This article shows how to create a simple chatbot in Python using the library ChatterBot. Our bot will be used for small talk, as well as to answer some math questions. Here, we’ll scratch the surface of what’s possible in building custom chatbots and NLP in general.

Preparing Dependencies

You’re only going to install the library ChatterBot for now. I recommend creating and using a new Python virtual environment for this purpose. Execute the following commands in your Python (or Anaconda) terminal:

pip install chatterbot
pip install chatterbot_corpus

You can also try upgrading them:

pip install --upgrade chatterbot_corpus
pip install --upgrade chatterbot

That’s it. We’re ready to go.

Importing Classes

You’ll need to import two classes for this purpose: ChatBot from chatterbot and ListTrainer from chatterbot.trainers:

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer

We’re now prepared to create and train our math bot.

Creating and Training a Bot

Our bot will be an instance of the class ChatBot:

my_bot = ChatBot(name='PyBot', read_only=True,

The only required argument corresponds to the parameter name. It represents the name of the bot. You can provide read_only=True if you want to disable the bot’s ability to learn after the training (i.e. from actual conversations). logic_adapters is the list of adapters used to train the bot. There are several of them provided by chatterbot, like the two from our example. chatterbot.logic.MathematicalEvaluation enables the bot to solve math problems, while chatterbot.logic.BestMatch chooses the best match from the already provided responses.

So, we have to provide responses. We do that by specifying the lists of strings later used to train the bot and find the best match for each question. This is what I want our bot to learn for now:

small_talk = ['hi there!',
          'how do you do?',
          'how are you?',
          'i\'m cool.',
          'fine, you?',
          'always cool.',
          'i\'m ok',
          'glad to hear that.',
          'i\'m fine',
          'glad to hear that.',
          'i feel awesome',
          'excellent, glad to hear that.',
          'not so good',
          'sorry to hear that.',
          'what\'s your name?',
          'i\'m pybot. ask me a math question, please.']
math_talk_1 = ['pythagorean theorem',
          'a squared plus b squared equals c squared.']
math_talk_2 = ['law of cosines',
          'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']

We can create and train the bot by creating an instance of ListTrainer and supplying it with the lists of strings:

list_trainer = ListTrainer(my_bot)

for item in (small_talk, math_talk_1, math_talk_2):

The bot should now be trained and ready to communicate.

Communicating with a Bot

You can communicate with your bot using its method .get_response(). Here’s an example of how that might look like:

>>> print(my_bot.get_response("hi"))
how do you do?

>>> print(my_bot.get_response("i feel awesome today"))
excellent, glad to hear that.

>>> print(my_bot.get_response("what's your name?"))
i'm pybot. ask me a math question, please.

>>> print(my_bot.get_response("show me the pythagorean theorem"))
a squared plus b squared equals c squared.

>>> print(my_bot.get_response("do you know the law of cosines?"))
c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)

Don’t expect the bot to answer each question well! Its knowledge is limited to the stuff similar to what it has learned. Many times, you’ll find it answering nonsense, especially if you don’t provide comprehensive training.

Training a Bot with a Corpus of Data

You can use your own or an existing corpus of data to train a bot. For example, you can use some corpus provided by chatterbot:

from chatterbot.trainers import ChatterBotCorpusTrainer

corpus_trainer = ChatterBotCorpusTrainer(my_bot)

chatterbot offers this functionality in several languages. You can also specify a subset of a corpus you’d like to use.


Now you know how to create and use a simple chat bot.

This is just a small illustration of what you can do with natural language processing and chatbots. There are many more possibilities out there. If you’re interested in exploring them, you can start by getting familiar with NLTK and ChatterBot.

Thank you for reading!

The article was prepared by our teammate Mirko.

Angular tutorial

Some time ago, I created the first tutorial about React.js where I showed you how to create an easy React.js application using an existing API and Bootstrap for styling. The positive response for this article brought me to the idea of creating a series of simple...

What skills you need to be a good developer?

Every profession has special requirements; for example, to be a doctor, you have to know biology, finish medical university, but besides the hard skills, as a doctor, you have to be emphatic. As a teacher, you need to have qualifications to work with kids, but you...

Angular tutorial

Angular tutorial

Some time ago, I created the first tutorial about React.js where I showed you how to create an easy React.js application using an existing API and Bootstrap for styling. The positive response for this article brought me to the idea of creating a series of simple...

React.js performance tutorial

React.js performance tutorial

Building applications sometimes can be a bit challenging, especially when we need to build a fast and good-quality application. These times it can be necessary, especially when search engines can give bonus SEO points for faster working apps, and it can help us to...

Vue.js tutorial: How to create Vue.js app in 5 minutes?

Vue.js tutorial: How to create Vue.js app in 5 minutes?

Vue.js is getting more and more popular, becoming a meaning competitor to frameworks like Angular or React.js. As a beginner-friendly front-end framework, it successfully conquers the hearts of junior front-end developers and people who just started to learn front-end...

8 CSS image filters with code examples

8 CSS image filters with code examples

Using images, we can create an atmosphere, arouse happiness, smile, sadness, or any different emotion. With images, we can show a lot, and tell a lot as well; that’s why pictures are so widely used in the websites and applications. Designers take care of how users...

CSS Grid tutorial

CSS Grid tutorial

When we build front-end, always we need to create a structure of our page, and very often, we need to create any grid. We can position elements in a few ways. For example, in the previous article I showed you how we could do it via flexbox. So, today, I would like to...

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!

Share This