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.




👉 Read More
How to extract Speech from Video using Python?
How to download video from youtube using python module ?
Deploy Django project on AWS with Apache2 and mod_wsgi module.
5 Selenium Project Ideas & for Beginners in Automation Testing
Best Python package manager and package for virtual environment ?
Mostly asked Python Interview Questions - 2023.
Core Python Syllabus for Interviews
Python Built-in functions lambda, map, filter, reduce.
How to reverse string in Python ?
GoodbyeX: A Step-by-Step Guide to Remove the "X" Branding from Twitter
Python 3.9 new amazing features ?
10 Proven Ways to Earn Money Through Python
5 Languages that Replace Python with Proof
Monkey Patching in Python: A Powerful Yet Controversial Technique
Best Practices for Managing Requests Library Sessions When Interacting with Multiple APIs ?
How to Ensure Proper Namespace Handling in XML with Python's lxml Library
How to Update XML Files in Python?
Explore more Blogs...