Building a Simple Chatbot with Python and openpyxl

Author: neptune | 25th-Jun-2024
#Python #Projects

In this article, we'll build a simple chatbot using Python. This chatbot will read questions and answers from an Excel file and respond to user inputs accordingly. Instead of using the pandas library, we'll utilize the openpyxl library to handle Excel file operations.

Prerequisites

Before we start, ensure you have the following installed:


- Python 3.x

- openpyxl library


You can install the openpyxl library using pip:

    pip install openpyxl



Step-by-Step Guide

Step 1: Setting Up the Excel File

First, create an Excel file named `questions_answers.xlsx` with two columns labeled "Questions" and "Answers". Fill in your questions and corresponding answers. For example:


Questions 

Answers 

What is your name?

My name is ChatBot.

How are you?  

I'm just a program, so I don't have feelings, but thank you for asking!

What is Python?  

Python is a programming language.


Step 2: Writing the Python Code


Here's the Python code to create the chatbot:


    import openpyxl


    # Load the Excel file

    def load_excel(file_path):

        try:

            wb = openpyxl.load_workbook(file_path)

            print(wb)

            sheet = wb["Questions"] # Change the sheet name

            return sheet

        except Exception as e:

            print("Exception in reading excel file :", e)

           


    # Get the answer from the Excel file based on the user's question

    def get_answer(sheet, user_question):

        for row in sheet.iter_rows(min_row=2, values_only=True): # Skip the header row

            question, answer = row

            if question.strip().lower() == user_question.strip().lower():

                return answer

        return "Sorry, I don't have an answer for that question."


    def chatbot():

        file_path = ".\Questions_Answers.xlsx"  # Replace with your Excel file path

        sheet = load_excel(file_path)

       

        print("Welcome to the chatbot! Type 'exit' to end the conversation.")

       

        while True:

            user_question = input("You: ")

            if user_question.lower() == 'exit':

                print("Chatbot: Goodbye!")

                break

            response = get_answer(sheet, user_question)

            print(f"Chatbot: {response}")


    # Run the chatbot

    if __name__ == "__main__":

        chatbot()



Explanation


1. Loading the Excel File: The `load_excel` function uses the `openpyxl.load_workbook` method to load the Excel file. It returns the active sheet from the workbook.

   

2. Getting the Answer: The `get_answer` function takes the active sheet and the user's question as inputs. It iterates through the rows of the sheet (starting from the second row to skip the header) and checks if the question matches any entry in the "Questions" column. If a match is found, it returns the corresponding answer from the "Answers" column. If no match is found, it returns a default message.


3. Chatbot Function: The `chatbot` function manages the interaction with the user. It loads the Excel file, prompts the user for input, and prints the corresponding response until the user types 'exit'.


Running the Chatbot

Save the above code in a Python file, for example, `chatbot.py`. Ensure your `questions_answers.xlsx` file is in the same directory as your Python script. Run the script using the following command:


    python chatbot.py



You'll see a welcome message, and you can start typing your questions. The chatbot will respond based on the data in your Excel file.


Conclusion

In this article, we created a simple chatbot using Python and the openpyxl library. This chatbot reads questions and answers from an Excel file and provides responses based on user input. While this is a basic implementation, it demonstrates how you can use openpyxl to interact with Excel files in Python. You can expand this project by adding more functionalities, such as natural language processing, to improve the chatbot's ability to understand and respond to user queries.




Related Blogs
How to extract Speech from Video using Python?
Author: neptune | 16th-Jun-2023
#Python #Projects
Simple and easy way to convert video into audio then text using Google Speech Recognition API...

How to download video from youtube using python module ?
Author: neptune | 15th-Jun-2023
#Python
We will let you know how you can easily download the Youtube high quality videos along with subtitle, thumbnail, description using python package..

5 Selenium Project Ideas & for Beginners in Automation Testing
Author: neptune | 30th-Mar-2023
#Selenium #Testing #Projects
In this article, we will discuss 5 interesting Selenium project ideas for beginners in automation testing...

Best Python package manager and package for virtual environment ?
Author: neptune | 18th-Jun-2023
#Python #Pip
We will explore the options of Pip, Virtualenv, Anaconda, and also introduce Pyenv as a helpful tool...

Deploy Django project on AWS with Apache2 and mod_wsgi module.
Author: neptune | 18th-May-2024
#Python #Django
In this blog I use the AWS Ubuntu 18.22 instance as Hosting platform and used Apache2 server with mod_wsgi for configurations. We create a django sample project then configure server...

Core Python Syllabus for Interviews
Author: neptune | 26th-Jul-2023
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...

Mostly asked Python Interview Questions - 2023.
Author: neptune | 30th-May-2023
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...

How to reverse string in Python ?
Author: neptune | 16th-May-2022
#Python
We are going to explore different ways to reverse string in Python...

Python Built-in functions lambda, map, filter, reduce.
Author: neptune | 15th-Jun-2023
#Python
We are going to explore in deep some important Python build-in functions lambda, map, filter and reduce with examples...

Python 3.9 new amazing features ?
Author: neptune | 26th-Jul-2023
#Python
Python 3.9 introduces new features such as dictionary union, string methods to remove prefixes and suffixes, type hinting, and speed improvements for built-in functions...

5 Languages that Replace Python with Proof
Author: neptune | 13th-Apr-2023
#Python
Julia, Rust, Go, Kotlin, and TypeScript are modern languages that could replace Python for specific use cases...

10 Proven Ways to Earn Money Through Python
Author: neptune | 11th-Apr-2023
#Python
Python offers numerous earning opportunities from web development to teaching, data analysis, machine learning, automation, web scraping, and more...

Monkey Patching in Python: A Powerful Yet Controversial Technique
Author: neptune | 01st-Aug-2023
#Python
Monkey patching in Python is a dynamic technique to modify code at runtime. It can add/alter behavior, but use it judiciously to avoid maintainability issues...

GoodbyeX: A Step-by-Step Guide to Remove the "X" Branding from Twitter
Author: neptune | 26th-Jul-2023
#Github #Projects
Twitter has been known for its continuous updates and changes to its user interface. One such change was the introduction of the "X" branding, which might not be appreciated by all users...

Best Practices for Managing Requests Library Sessions When Interacting with Multiple APIs ?
Author: neptune | 22nd-Aug-2024
#Python
When working with Python's `requests` library, managing sessions is crucial, especially when your application interacts with multiple APIs...

How to Update XML Files in Python?
Author: neptune | 01st-Jul-2024
#Python
Handling XML files in Python is straightforward with the `xml.etree.ElementTree` module...

How to Ensure Proper Namespace Handling in XML with Python's lxml Library
Author: neptune | 01st-Jul-2024
#Python
By using `lxml`, you can effectively manage XML namespaces and ensure that your XML structure remains intact during updates...

View More