DEV Community

John Peters
John Peters

Posted on

Create a Question/Answer Chatbot in Python

Using the NTLK Natural Language Toolkit

Step 1: Install Required Libraries

pip install nltk

Step 2: Import Libraries and Prepare Data

In this example, we’ll use NLTK for tokenization and some basic text processing.

import nltk
from nltk.chat.util import Chat, reflections
Enter fullscreen mode Exit fullscreen mode

Download the NLTK tokenizer

nltk.download('punkt')
Enter fullscreen mode Exit fullscreen mode

Step 3: Define Chatbot Responses

You'll create a list of patterns and corresponding responses. The chatbot will match user input against the patterns and provide the appropriate response.

Define the patterns and responses

pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, how can I help you today?",]
    ],
    [
        r"hi|hey|hello",
        ["Hello! How can I assist you?",]
    ],
    [
        r"what is your name?",
        ["I am a chatbot created to assist you.",]
    ],
    [
        r"how are you?",
        ["I'm just a program, but thanks for asking!",]
    ],
    [
        r"sorry (.*)",
        ["No problem!",]
    ],
    [
        r"bye|goodbye",
        ["Goodbye! Have a nice day!",]
    ],
    [
        r"(.*) your (.*) favorite color?",
        ["I don't have preferences, but what's yours?",]
    ],
    [
        r"(.*)",
        ["I'm sorry, I don't understand that. Can you ask something else?",]
    ],
]
Enter fullscreen mode Exit fullscreen mode

Initialize reflections and chatbot

python chatbot = Chat(pairs, reflections)

Step 4: Run the Chatbot

Finally, create a loop that allows users to interact with the chatbot.


def chatbot_conversation():
    print("Welcome to the Python Chatbot! Type 'bye' to exit.")
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'bye':
            print("Chatbot: Goodbye!")
            break
        else:
            response = chatbot.respond(user_input)
            print(f"Chatbot: {response}")
#start
chatbot_conversation()
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Your Chatbot

Run the script, and you should be able to interact with your basic Python chatbot. The chatbot will respond based on the predefined patterns and responses.

Expanding the Chatbot
You can expand this chatbot by adding more complex patterns, integrating machine learning models for better understanding, or even using APIs like OpenAI's GPT for more advanced interactions.

Let me know if you need further help with this or any other enhancements!

Top comments (0)