Building a Simple Chatbot using Python

Nethmi Nikeshala ( Keshala )
3 min readJul 30, 2023

--

Today, I would like to write how build a simple chatbot easily. In this article, I will guide you through the process of creating a simple chatbot using Python, step by step, with examples.

Chatbots have become increasingly popular in recent years, providing automated responses to user inquiries and helping businesses improve customer service and engagement. Building a chatbot from scratch might sound daunting, but Python makes it relatively easy with its extensive libraries and frameworks.

Before I dive into building the chatbot, ensure you have the following installed on your system:

  1. Python (version 3.x recommended)
  2. pip (Python package manager)

Setting Up the Environment

First, let’s create a new directory for our project. Open a terminal or command prompt and run the following command:

$ mkdir simple_chatbot
cd simple_chatbot

Next, I will set up a virtual environment to keep our project dependencies isolated. This step is optional but recommended to prevent conflicts with other Python projects. Run the following commands:

python3 -m venv venv
source venv/bin/activate # On Windows, use: venv\Scripts\activate

Installing Required Libraries

I will use the nltk library for natural language processing and numpy for numerical operations. Install them using pip:

pip install nltk numpy

Preparing the Data

For my simple chatbot, I will use a predefined set of questions and responses. You can expand this data later for a more sophisticated chatbot.

Create a new file named data.py inside the simple_chatbot directory and define the following data:

data = {
"greetings": ["hello", "hi", "hey", "howdy", "hola"],
"responses": ["Hello!", "Hi there!", "Hey!", "Greetings!"],
}

Implementing the Chatbot

Create another Python file named chatbot.py in the same directory and start building the chatbot logic.

import random
import string
import nltk
from nltk.stem import PorterStemmer

# Initialize NLTK
nltk.download("punkt")
stemmer = PorterStemmer()

# Load data from data.py
from data import data

# Tokenize and stem the user input
def preprocess(sentence):
tokens = nltk.word_tokenize(sentence.lower())
return [stemmer.stem(token) for token in tokens]

# Generate a response based on user input
def get_response(user_input):
user_input = preprocess(user_input)

for intent, patterns in data.items():
for pattern in patterns:
if all(word in user_input for word in preprocess(pattern)):
return random.choice(data[intent])

return "I'm sorry, I don't understand."

# Chat loop
def chat():
print("Chatbot: Hello! I'm your friendly chatbot. Type 'exit' to end the conversation.")

while True:
user_input = input("You: ")

if user_input.lower() == "exit":
break

response = get_response(user_input)
print("Chatbot:", response)

if __name__ == "__main__":
chat()

Testing the Chatbot

Run the chatbot using the following command:

python chatbot.py

Now, you can interact with your chatbot! Type a greeting like “hi” or “hello,” and it should respond accordingly. Feel free to extend the data dictionary with more patterns and responses for a more diverse chatbot experience.

Though this is just a starting point, you can enhance your chatbot by integrating it with APIs, incorporating machine learning models for more advanced natural language processing, or deploying it on various platforms.

Remember that chatbot development is an ongoing process, and continuous improvement will make your chatbot smarter and more useful.

If you enjoyed reading this article and have found it useful, then please give it a clap, share it with your friends, and follow me to get more updates on my upcoming articles. You can connect with me on LinkedIn.

.

Thank You !!!……….

--

--

Nethmi Nikeshala ( Keshala )

DevOps Engineer | UG | Junior Researcher | Sri Lanka Institute of Information Technology | Wayamba University