Creating a Basic hardcoded ChatBot using Python-NLTK

Creating a basic chatbot using Python in Jupyter Notebook. This chatbot interacts with the user using the hardcoded inputs and outputs which are fed into the Python code.

Requirements:
You need to install the NLTK (Natural Language Toolkit), it provides libraries and programs for symbolic and statistical natural language processing for English written in the Python programming language. To install this module type the below command in the terminal.

pip install nltk

Below is the implementation

filter_none

edit
close

play_arrow

link
brightness_4
code

from nltk.chat.util import Chat, reflections
  
pairs =[
    ['my name is (.*)', ['Hello ! % 1']],
    ['(hi|hello|hey|holla|hola)', ['Hey there !', 'Hi there !', 'Hey !']],
    ['(.*) your name ?', ['My name is Geeky']],
    ['(.*) do you do ?', ['We provide a platform for tech enthusiasts, a wide range of options !']],
    ['(.*) created you ?', ['Geeksforgeeks created me using python and NLTK']]
]
  
chat = Chat(pairs, reflections)
chat.converse()

chevron_right


Output:

Explanation of the above code:
In the first line of code we have imported the Chat class and Reflections dictionary from the Natural Language Toolkit’s chatbot utilities. Chat class which will process the conversation between the user and your chatbot. Reflections is a dictionary that when a value in a regular expression group matches a key in the dictionary it will output the value in the response. So for the first item of list pairs if we input my name is geeky where geeky corresponds to the regex “(.*)” it will output “Hello ! Geeky”, that is it replaces the regex in response to “%1” that was referred to as “(.*)” with “Geeky”. Now we initialize the chatbot using pairs and reflections dictionary. Then after initialization we call the converse method of Chat class that automates the chatbot.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.