Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here's a sample Python chatbot program using the Natural Language Toolkit (NLTK) library:

import nltk
from nltk.chat.util import Chat, reflections

pairs = [
    ['my name is (.*)', ['Hi %1']],
    ['(hi|hello|hey)', ['Hello', 'Hi there']],
    ['what is your name?', ['My name is Chatbot']],
    ['how are you?', ['I am good. How are you?']],
    ['i am (.*)(good|well)', ['That\'s great to hear!']],
    ['i am (.*)', ['Nice to meet you, %1']],
    ['bye', ['Goodbye!', 'Bye', 'See you later']],
]

chatbot = Chat(pairs, reflections)
chatbot.converse()

This program defines a set of pattern-response pairs and uses the Chat class from NLTK to create the chatbot. When you run the program, it will ask for input from the user and try to match it to one of the patterns. If it does, it will respond with a corresponding response. For example:

> hi
Hello

> my name is John
Hi John

> how are you?
I am good. How are you?

> i am doing well
That's great to hear!

> bye
Goodbye!

If you encounter a runtime error, for example, "ModuleNotFoundError: No module named 'nltk'", it could be because you haven't installed the NLTK library. To install NLTK, you can use pip by running the command pip install nltk in your terminal or command prompt. If you already have NLTK installed, make sure that you have imported it correctly by adding import nltk at the beginning of your program.