Software Engineering

How to Create a Simple Chatbot in Python


This is a simple chatbot in Python using the NLTK library.

See the below example Python code:

# Import necessary libraries
from nltk.chat.util import Chat, reflections

# Define your chatbot's responses
responses = {
    "hello": "Hello, how can I assist you?",
    "hi": "Hi there! How can I help you today?",
    "how are you": "I'm doing well, thank you for asking.",
    "what can you do": "I can help you with tasks such as finding information, setting reminders, and more!",
    "bye": "Goodbye, have a nice day!",
}

# Create a Chat instance with your responses
chatbot = Chat(responses, reflections)

# Start chatting!
chatbot.converse()

In this example, we’ve defined a dictionary of responses for our chatbot to use. The keys of the dictionary are the inputs that the user might enter, and the values are the chatbot’s responses. We then create a Chat instance with these responses and the reflections dictionary, which helps the chatbot handle variations of user input (such as changing “you are” to “I am” in responses).

Finally, we call the converse method on our chatbot to start the conversation. The chatbot will prompt the user for input, and then respond with an appropriate message based on the responses dictionary.

Note that this is a very simple example of a chatbot, and you can customize it further by adding more responses, using regular expressions to handle more complex input, and incorporating machine learning algorithms to make your chatbot smarter over time.