

{"id":73520,"date":"2019-12-10T14:43:07","date_gmt":"2019-12-10T09:13:07","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=73520"},"modified":"2025-07-29T20:54:33","modified_gmt":"2025-07-29T15:24:33","slug":"python-chatbot-project","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/","title":{"rendered":"Python Chatbot Project &#8211; Learn to build your first chatbot using NLTK &amp; Keras"},"content":{"rendered":"<p style=\"text-align: left\"><em>Hey Siri, What&#8217;s the meaning of Life?<\/em><\/p>\n<p style=\"text-align: left\"><em>As per all the evidence, it&#8217;s chocolate for you.<\/em><\/p>\n<p>Soon as I heard this reply from Siri, I knew I found a perfect partner to savour my hours of solitude. From stupid questions to some pretty serious advice, Siri has been always there for me.<\/p>\n<p>How amazing it is to tell someone everything and anything and not being judged at all. A top class feeling it is and that&#8217;s what the beauty of a chatbot is.<\/p>\n<p>This is the 9th project in the 20 Python projects series by DataFlair and make sure to bookmark other interesting projects:<\/p>\n<ol>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/advanced-python-project-detecting-fake-news\/\">Fake News Detection Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-machine-learning-project-detecting-parkinson-disease\/\">Parkinson\u2019s Disease Detection Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/project-in-python-colour-detection\/\">Color Detection Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-mini-project-speech-emotion-recognition\/\">Speech Emotion Recognition Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/project-in-python-breast-cancer-classification\/\">Breast Cancer Classification Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-project-gender-age-detection\/\">Age and Gender Detection Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-deep-learning-project-handwritten-digit-recognition\/\">Handwritten Digit Recognition Python Project<\/a><\/li>\n<li>Chatbot Python Project<\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-project-driver-drowsiness-detection-system\/\">Driver Drowsiness Detection Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-project-traffic-signs-recognition\/\">Traffic Signs Recognition Python Project<\/a><\/li>\n<li><a href=\"https:\/\/data-flair.training\/blogs\/python-based-project-image-caption-generator-cnn\/\">Image Caption Generator Python Project<\/a><\/li>\n<\/ol>\n<h3>What is Chatbot?<\/h3>\n<p>A chatbot is an intelligent piece of software that is capable of communicating and performing actions similar to a human. Chatbots are used a lot in customer interaction, marketing on social network sites and instantly messaging the client. There are two basic types of chatbot models based on how they are built; Retrieval based and Generative based models.<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.gif\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-74014 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.gif\" alt=\"Python chatbot project\" width=\"1020\" height=\"640\" \/><\/a><\/p>\n<h4>1. Retrieval based Chatbots<\/h4>\n<p>A retrieval-based chatbot uses predefined input patterns and responses. It then uses some type of heuristic approach to select the appropriate response. It is widely used in the industry to make goal-oriented chatbots where we can customize the tone and flow of the chatbot to drive our customers with the best experience.<\/p>\n<h4>2. Generative based Chatbots<\/h4>\n<p>Generative models are not based on some predefined responses.<\/p>\n<p>They are based on seq 2 seq neural networks. It is the same idea as machine translation. In machine translation, we translate the source code from one language to another language but here, we are going to transform input into an output. It needs a large amount of data and it is based on Deep Neural networks.<\/p>\n<h3>About the Python Project &#8211; Chatbot<\/h3>\n<p>In this Python project with source code, we are going to build a chatbot using deep learning techniques. The chatbot will be trained on the dataset which contains categories (intents), pattern and responses. We use a special recurrent neural network (LSTM) to classify which category the user\u2019s message belongs to and then we will give a random response from the list of responses.<\/p>\n<p>Let\u2019s create a retrieval based chatbot using NLTK, Keras, Python, etc.<\/p>\n<h3>Download Chatbot Code &amp; Dataset<\/h3>\n<p>The dataset we will be using is \u2018intents.json\u2019. This is a JSON file that contains the patterns we need to find and the responses we want to return to the user.<\/p>\n<p>Please download python chatbot code &amp; dataset from the following link:\u00a0<strong><a href=\"https:\/\/data-flair.training\/blogs\/download-python-chatbot-data-project-source-code\/\" target=\"_blank\" rel=\"noopener noreferrer\">Python Chatbot Code &amp; Dataset<\/a><\/strong><\/p>\n<h3>Prerequisites<\/h3>\n<p>The project requires you to have good knowledge of Python, Keras, and <a href=\"https:\/\/data-flair.training\/blogs\/nltk-python-tutorial\/\"><em><strong>Natural language processing (NLTK)<\/strong><\/em><\/a>. Along with them, we will use some helping modules which you can download using the python-pip command.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">pip install tensorflow, keras, pickle, nltk<\/pre>\n<h3>How to Make Chatbot in Python?<\/h3>\n<p>Now we are going to build the chatbot using Python but first, let us see the file structure and the type of files we will be creating:<\/p>\n<p style=\"text-align: center\"><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"img-gray-border aligncenter wp-image-73574 size-full\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1.png\" alt=\"Types of files - Python Chatbot\" width=\"1366\" height=\"728\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1.png 1366w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1-150x80.png 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1-300x160.png 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1-768x409.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1-1024x546.png 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Types-of-files-1-520x277.png 520w\" sizes=\"auto, (max-width: 1366px) 100vw, 1366px\" \/><\/a><\/p>\n<ul>\n<li><strong>Intents.json &#8211;<\/strong> The data file which has predefined patterns and responses.<\/li>\n<li><strong>train_chatbot.py &#8211;<\/strong> In this Python file, we wrote a script to build the model and train our chatbot.<\/li>\n<li><strong>Words.pkl &#8211;<\/strong> This is a pickle file in which we store the words Python object that contains a list of our vocabulary.<\/li>\n<li><strong>Classes.pkl &#8211;<\/strong> The classes pickle file contains the list of categories.<\/li>\n<li><strong>Chatbot_model.h5 &#8211;<\/strong> This is the trained model that contains information about the model and has weights of the neurons.<\/li>\n<li><strong>Chatgui.py &#8211;<\/strong> This is the Python script in which we implemented GUI for our chatbot. Users can easily interact with the bot.<\/li>\n<\/ul>\n<p>Here are the 5 steps to create a chatbot in Python from scratch:<\/p>\n<ol>\n<li>Import and load the data file<\/li>\n<li>Preprocess data<\/li>\n<li>Create training and testing data<\/li>\n<li>Build the model<\/li>\n<li>Predict the response<\/li>\n<\/ol>\n<p><strong>1. Import and load the data file<\/strong><\/p>\n<p>First, make a file name as train_chatbot.py. We import the necessary packages for our chatbot and initialize the variables we will use in our Python project.<\/p>\n<p>The data file is in JSON format so we used the json package to parse the JSON file into Python.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import nltk\r\nfrom nltk.stem import WordNetLemmatizer\r\nlemmatizer = WordNetLemmatizer()\r\nimport json\r\nimport pickle\r\n\r\nimport numpy as np\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Activation, Dropout\r\nfrom keras.optimizers import SGD\r\nimport random\r\n\r\nwords=[]\r\nclasses = []\r\ndocuments = []\r\nignore_words = ['?', '!']\r\ndata_file = open('intents.json').read()\r\nintents = json.loads(data_file)<\/pre>\n<p>This is how our intents.json file looks like.<\/p>\n<p style=\"text-align: center\"><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-73562\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file.png\" alt=\"intents data file - Python chatbot project\" width=\"1366\" height=\"728\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file.png 1366w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file-150x80.png 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file-300x160.png 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file-768x409.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file-1024x546.png 1024w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/intents-data-file-520x277.png 520w\" sizes=\"auto, (max-width: 1366px) 100vw, 1366px\" \/><\/a><\/p>\n<p><strong>2. Preprocess data<\/strong><\/p>\n<p>When working with text data, we need to perform various preprocessing on the data before we make a machine learning or a deep learning model. Based on the requirements we need to apply various operations to preprocess the data.<\/p>\n<p>Tokenizing is the most basic and first thing you can do on text data. Tokenizing is the process of breaking the whole text into small parts like words.<\/p>\n<p>Here we iterate through the patterns and tokenize the sentence using nltk.word_tokenize() function and append each word in the words list. We also create a list of classes for our tags.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">for intent in intents['intents']:\r\n    for pattern in intent['patterns']:\r\n\r\n        #tokenize each word\r\n        w = nltk.word_tokenize(pattern)\r\n        words.extend(w)\r\n        #add documents in the corpus\r\n        documents.append((w, intent['tag']))\r\n\r\n        # add to our classes list\r\n        if intent['tag'] not in classes:\r\n            classes.append(intent['tag'])<\/pre>\n<p>Now we will lemmatize each word and remove duplicate words from the list. Lemmatizing is the process of converting a word into its lemma form and then creating a pickle file to store the Python objects which we will use while predicting.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\"># lemmatize, lower each word and remove duplicates\r\nwords = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]\r\nwords = sorted(list(set(words)))\r\n# sort classes\r\nclasses = sorted(list(set(classes)))\r\n# documents = combination between patterns and intents\r\nprint (len(documents), \"documents\")\r\n# classes = intents\r\nprint (len(classes), \"classes\", classes)\r\n# words = all words, vocabulary\r\nprint (len(words), \"unique lemmatized words\", words)\r\n\r\npickle.dump(words,open('words.pkl','wb'))\r\npickle.dump(classes,open('classes.pkl','wb'))<\/pre>\n<p><strong>3. Create training and testing data<\/strong><\/p>\n<p>Now, we will create the training data in which we will provide the input and the output. Our input will be the pattern and output will be the class our input pattern belongs to. But the computer doesn\u2019t understand text so we will convert text into numbers.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\"># create our training data\r\ntraining = []\r\n# create an empty array for our output\r\noutput_empty = [0] * len(classes)\r\n# training set, bag of words for each sentence\r\nfor doc in documents:\r\n    # initialize our bag of words\r\n    bag = []\r\n    # list of tokenized words for the pattern\r\n    pattern_words = doc[0]\r\n    # lemmatize each word - create base word, in attempt to represent related words\r\n    pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]\r\n    # create our bag of words array with 1, if word match found in current pattern\r\n    for w in words:\r\n        bag.append(1) if w in pattern_words else bag.append(0)\r\n\r\n    # output is a '0' for each tag and '1' for current tag (for each pattern)\r\n    output_row = list(output_empty)\r\n    output_row[classes.index(doc[1])] = 1\r\n\r\n    training.append([bag, output_row])\r\n# shuffle our features and turn into np.array\r\nrandom.shuffle(training)\r\ntraining = np.array(training)\r\n# create train and test lists. X - patterns, Y - intents\r\ntrain_x = list(training[:,0])\r\ntrain_y = list(training[:,1])\r\nprint(\"Training data created\")<\/pre>\n<p><strong>4. Build the model<\/strong><\/p>\n<p>We have our training data ready, now we will build a deep neural network that has 3 layers. We use the Keras sequential API for this. After training the model for 200 epochs, we achieved 100% accuracy on our model. Let us save the model as \u2018chatbot_model.h5\u2019.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\"># Create model - 3 layers. First layer 128 neurons, second layer 64 neurons and 3rd output layer contains number of neurons\r\n# equal to number of intents to predict output intent with softmax\r\nmodel = Sequential()\r\nmodel.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(64, activation='relu'))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(len(train_y[0]), activation='softmax'))\r\n\r\n# Compile model. Stochastic gradient descent with Nesterov accelerated gradient gives good results for this model\r\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\r\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\r\n\r\n#fitting and saving the model \r\nhist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)\r\nmodel.save('chatbot_model.h5', hist)\r\n\r\nprint(\"model created\")<\/pre>\n<p><strong>5. Predict the response (Graphical User Interface)<\/strong><\/p>\n<p>To predict the sentences and get a response from the user to let us create a new file \u2018chatapp.py\u2019.<\/p>\n<p>We will load the trained model and then use a graphical user interface that will predict the response from the bot. The model will only tell us the class it belongs to, so we will implement some functions which will identify the class and then retrieve us a random response from the list of responses.<\/p>\n<p>Again we import the necessary packages and load the \u2018words.pkl\u2019 and \u2018classes.pkl\u2019 pickle files which we have created when we trained our model:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import nltk\r\nfrom nltk.stem import WordNetLemmatizer\r\nlemmatizer = WordNetLemmatizer()\r\nimport pickle\r\nimport numpy as np\r\n\r\nfrom keras.models import load_model\r\nmodel = load_model('chatbot_model.h5')\r\nimport json\r\nimport random\r\nintents = json.loads(open('intents.json').read())\r\nwords = pickle.load(open('words.pkl','rb'))\r\nclasses = pickle.load(open('classes.pkl','rb'))<\/pre>\n<p>To predict the class, we will need to provide input in the same way as we did while training. So we will create some functions that will perform text preprocessing and then predict the class.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def clean_up_sentence(sentence):\r\n    # tokenize the pattern - split words into array\r\n    sentence_words = nltk.word_tokenize(sentence)\r\n    # stem each word - create short form for word\r\n    sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]\r\n    return sentence_words\r\n# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence\r\n\r\ndef bow(sentence, words, show_details=True):\r\n    # tokenize the pattern\r\n    sentence_words = clean_up_sentence(sentence)\r\n    # bag of words - matrix of N words, vocabulary matrix\r\n    bag = [0]*len(words) \r\n    for s in sentence_words:\r\n        for i,w in enumerate(words):\r\n            if w == s: \r\n                # assign 1 if current word is in the vocabulary position\r\n                bag[i] = 1\r\n                if show_details:\r\n                    print (\"found in bag: %s\" % w)\r\n    return(np.array(bag))\r\n\r\ndef predict_class(sentence, model):\r\n    # filter out predictions below a threshold\r\n    p = bow(sentence, words,show_details=False)\r\n    res = model.predict(np.array([p]))[0]\r\n    ERROR_THRESHOLD = 0.25\r\n    results = [[i,r] for i,r in enumerate(res) if r&gt;ERROR_THRESHOLD]\r\n    # sort by strength of probability\r\n    results.sort(key=lambda x: x[1], reverse=True)\r\n    return_list = []\r\n    for r in results:\r\n        return_list.append({\"intent\": classes[r[0]], \"probability\": str(r[1])})\r\n    return return_list<\/pre>\n<p>After predicting the class, we will get a random response from the list of intents.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">def getResponse(ints, intents_json):\r\n    tag = ints[0]['intent']\r\n    list_of_intents = intents_json['intents']\r\n    for i in list_of_intents:\r\n        if(i['tag']== tag):\r\n            result = random.choice(i['responses'])\r\n            break\r\n    return result\r\n\r\ndef chatbot_response(text):\r\n    ints = predict_class(text, model)\r\n    res = getResponse(ints, intents)\r\n    return res<\/pre>\n<p>Now we will develop a graphical user interface. Let&#8217;s use Tkinter library which is shipped with tons of useful libraries for GUI. We will take the input message from the user and then use the helper functions we have created to get the response from the bot and display it on the GUI. Here is the full source code for the GUI.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">#Creating GUI with tkinter\r\nimport tkinter\r\nfrom tkinter import *\r\n\r\n\r\ndef send():\r\n    msg = EntryBox.get(\"1.0\",'end-1c').strip()\r\n    EntryBox.delete(\"0.0\",END)\r\n\r\n    if msg != '':\r\n        ChatLog.config(state=NORMAL)\r\n        ChatLog.insert(END, \"You: \" + msg + '\\n\\n')\r\n        ChatLog.config(foreground=\"#442265\", font=(\"Verdana\", 12 ))\r\n\r\n        res = chatbot_response(msg)\r\n        ChatLog.insert(END, \"Bot: \" + res + '\\n\\n')\r\n\r\n        ChatLog.config(state=DISABLED)\r\n        ChatLog.yview(END)\r\n\r\nbase = Tk()\r\nbase.title(\"Hello\")\r\nbase.geometry(\"400x500\")\r\nbase.resizable(width=FALSE, height=FALSE)\r\n\r\n#Create Chat window\r\nChatLog = Text(base, bd=0, bg=\"white\", height=\"8\", width=\"50\", font=\"Arial\",)\r\n\r\nChatLog.config(state=DISABLED)\r\n\r\n#Bind scrollbar to Chat window\r\nscrollbar = Scrollbar(base, command=ChatLog.yview, cursor=\"heart\")\r\nChatLog['yscrollcommand'] = scrollbar.set\r\n\r\n#Create Button to send message\r\nSendButton = Button(base, font=(\"Verdana\",12,'bold'), text=\"Send\", width=\"12\", height=5,\r\n                    bd=0, bg=\"#32de97\", activebackground=\"#3c9d9b\",fg='#ffffff',\r\n                    command= send )\r\n\r\n#Create the box to enter message\r\nEntryBox = Text(base, bd=0, bg=\"white\",width=\"29\", height=\"5\", font=\"Arial\")\r\n#EntryBox.bind(\"&lt;Return&gt;\", send)\r\n\r\n\r\n#Place all components on the screen\r\nscrollbar.place(x=376,y=6, height=386)\r\nChatLog.place(x=6,y=6, height=386, width=370)\r\nEntryBox.place(x=128, y=401, height=90, width=265)\r\nSendButton.place(x=6, y=401, height=90)\r\n\r\nbase.mainloop()<\/pre>\n<p><strong>6. Run the chatbot<\/strong><\/p>\n<p>To run the chatbot, we have two main files; <strong>train_chatbot.py<\/strong> and <strong>chatapp.py<\/strong>.<\/p>\n<p>First, we train the model using the command in the terminal:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">python train_chatbot.py<\/pre>\n<p>If we don\u2019t see any error during training, we have successfully created the model. Then to run the app, we run the second file.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">python chatgui.py<\/pre>\n<p>The program will open up a GUI window within a few seconds. With the GUI you can easily chat with the bot.<\/p>\n<p><strong>Screenshots:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-73563\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result.png\" alt=\"Python chatbot result\" width=\"849\" height=\"494\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result.png 849w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result-150x87.png 150w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result-300x175.png 300w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result-768x447.png 768w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chatbot-result-520x303.png 520w\" sizes=\"auto, (max-width: 849px) 100vw, 849px\" \/><\/a><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chat-between-user-bot.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-73564\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chat-between-user-bot.png\" alt=\"chat between user &amp; bot - Python Chatbot\" width=\"402\" height=\"532\" srcset=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chat-between-user-bot.png 402w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chat-between-user-bot-113x150.png 113w, https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/chat-between-user-bot-227x300.png 227w\" sizes=\"auto, (max-width: 402px) 100vw, 402px\" \/><\/a><\/p>\n<h3>Summary<\/h3>\n<p>In this Python data science project, we understood about chatbots and implemented a deep learning version of a chatbot in Python which is accurate. You can customize the data according to business requirements and train the chatbot with great accuracy. Chatbots are used everywhere and all businesses are looking forward to implementing bot in their workflow.<\/p>\n<p>This project is perfect for music lovers and ML beginners. It teaches audio data handling, feature extraction, classification, and music signal processing. It also helps explore how AI interacts with the world of sound.<\/p>\n<p>I hope you will practice by customizing your own chatbot using Python and don\u2019t forget to show us your work. And, if you found the article useful, do share the project with your friends and colleagues.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey Siri, What&#8217;s the meaning of Life? As per all the evidence, it&#8217;s chocolate for you. Soon as I heard this reply from Siri, I knew I found a perfect partner to savour my&#46;&#46;&#46;<\/p>\n","protected":false},"author":7,"featured_media":73551,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[36],"tags":[21496,9077,21495,21497,21082],"class_list":["post-73520","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-machine-learning","tag-chatbot-code-in-python","tag-nltk","tag-python-chatbot","tag-python-chatbot-tutorial","tag-python-project"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Chatbot Project - Learn to build your first chatbot using NLTK &amp; Keras - DataFlair<\/title>\n<meta name=\"description\" content=\"Learn to create a chatbot in Python using NLTK, Keras, deep learning techniques &amp; a recurrent neural network (LSTM) with easy steps. Also, learn about the chatbots &amp; its types with this Python project.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Chatbot Project - Learn to build your first chatbot using NLTK &amp; Keras - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Learn to create a chatbot in Python using NLTK, Keras, deep learning techniques &amp; a recurrent neural network (LSTM) with easy steps. Also, learn about the chatbots &amp; its types with this Python project.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2019-12-10T09:13:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-07-29T15:24:33+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Chatbot Project - Learn to build your first chatbot using NLTK &amp; Keras - DataFlair","description":"Learn to create a chatbot in Python using NLTK, Keras, deep learning techniques & a recurrent neural network (LSTM) with easy steps. Also, learn about the chatbots & its types with this Python project.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/","og_locale":"en_US","og_type":"article","og_title":"Python Chatbot Project - Learn to build your first chatbot using NLTK &amp; Keras - DataFlair","og_description":"Learn to create a chatbot in Python using NLTK, Keras, deep learning techniques & a recurrent neural network (LSTM) with easy steps. Also, learn about the chatbots & its types with this Python project.","og_url":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2019-12-10T09:13:07+00:00","article_modified_time":"2025-07-29T15:24:33+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/beb0cab24b7aa54423a3b50e669a9dcd"},"headline":"Python Chatbot Project &#8211; Learn to build your first chatbot using NLTK &amp; Keras","datePublished":"2019-12-10T09:13:07+00:00","dateModified":"2025-07-29T15:24:33+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/"},"wordCount":1435,"commentCount":280,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.jpg","keywords":["chatbot code in python","NLTK","Python Chatbot","python chatbot tutorial","Python project"],"articleSection":["Machine Learning Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/","url":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/","name":"Python Chatbot Project - Learn to build your first chatbot using NLTK &amp; Keras - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.jpg","datePublished":"2019-12-10T09:13:07+00:00","dateModified":"2025-07-29T15:24:33+00:00","description":"Learn to create a chatbot in Python using NLTK, Keras, deep learning techniques & a recurrent neural network (LSTM) with easy steps. Also, learn about the chatbots & its types with this Python project.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-chatbot-project\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2019\/12\/Python-chatbot-project.jpg","width":802,"height":420,"caption":"Python chatbot project"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-chatbot-project\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Machine Learning Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/machine-learning\/"},{"@type":"ListItem","position":3,"name":"Python Chatbot Project &#8211; Learn to build your first chatbot using NLTK &amp; Keras"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/beb0cab24b7aa54423a3b50e669a9dcd","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c322416204232f4dd97ef3901b0a499a5d34d7ba7fe333f4bfe53a907873d293?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c322416204232f4dd97ef3901b0a499a5d34d7ba7fe333f4bfe53a907873d293?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c322416204232f4dd97ef3901b0a499a5d34d7ba7fe333f4bfe53a907873d293?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team specializes in creating clear, actionable content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Backed by industry expertise, we make learning easy and career-oriented for beginners and pros alike.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam3\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/73520","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=73520"}],"version-history":[{"count":31,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/73520\/revisions"}],"predecessor-version":[{"id":146355,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/73520\/revisions\/146355"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/73551"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=73520"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=73520"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=73520"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}