Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Building a Rule-Based Chatbot with Natural Language Processing
Next article icon

Building a Rule-Based Chatbot with Natural Language Processing

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A rule-based chatbot follows a set of predefined rules or patterns to match user input and generate an appropriate response. The chatbot can’t understand or process input beyond these rules and relies on exact matches making it ideal for handling repetitive tasks or specific queries.

  • Pattern Matching: The chatbot compares the user’s input with predefined patterns and selects a matching response.
  • Predictable Responses: Since the chatbot operates based on a defined set of rules it provides predictable and consistent responses.
  • Limited Flexibility: Rule-based chatbots are not designed to handle complex conversations or evolve over time like AI-based chatbots. They work best for situations where user input can be anticipated.

Steps to implement Rule Based Chatbot in NLP

1. Installing Necessary Libraries

First we need to install the NLTK library which will help us with text processing tasks such as tokenization and part-of-speech tagging.

You can install the NLTK library using the following command:

pip install nltk

2. Importing Required Libraries

Once the libraries are installed, the next step is to import the necessary Python modules.

  • re: Used for regular expressions which help in matching patterns in user input.
  • Chat: A class from NLTK used to build rule-based chatbots.
  • reflections: A dictionary to map pronouns. For example, "I" → "you" making conversations more natural.
Python
import nltk import re from nltk.chat.util import Chat, reflections 


3. Downloading NLTK Datasets

Before proceeding we need to download specific NLTK datasets required for tokenization and part-of-speech (PoS) tagging.

  • punkt: Used for tokenization which breaking down text into words or sentences.
  • averaged_perceptron_tagger: PoS tagger helps to identify the grammatical parts of speech in a sentence.
Python
nltk.download('punkt') nltk.download('averaged_perceptron_tagger') 

Output:

Screenshot-2025-03-19-124650
NLTK Dataset

4. Defining Patterns and Responses

Rule-based chatbot recognize patterns in user input and respond accordingly. Here we will define a list of patterns and respective responses that the chatbot will use to interact with users. These patterns are written using regular expressions which allow the chatbot to match complex user queries and provide relevant responses.

  • Pattern Matching: The regular expressions (RegEx) here match user input. For example r"hi|hello|hey" matches greetings.
  • Responses: Each pattern has an associated list of responses which the chatbot will choose from.
Python
pairs = [     [r"hi|hello|hey", ["Hello! How can I help you today?", "Hi there! How may I assist you?"]],     [r"my name is (.*)", ["Hello %1! How can I assist you today?"]],     [r"(.*) your name?", ["I am your friendly chatbot!"]],     [r"how are you?", ["I'm just a bot, but I'm doing well. How about you?"]],     [r"tell me a joke", ["Why don't skeletons fight each other? They don't have the guts!"]],     [r"(.*) (help|assist) (.*)", ["Sure! How can I assist you with %3?"]],     [r"bye|exit", ["Goodbye! Have a great day!", "See you later!"]],     [r"(.*)", ["I'm sorry, I didn't understand that. Could you rephrase?", "Could you please elaborate?"]] ] 


5. Defining the Chatbot Class

Now, let’s create a class to handle the chatbot’s functionality. This class will use the Chat object from NLTK to match patterns and generate responses.

  • Chat Object: The Chat class is initialized with the patterns and reflections. It handles the matching of patterns to the user input and returns the corresponding response.
  • respond() method: This method takes user input and matches it with predefined patterns and returns the chatbot’s response.
Python
class RuleBasedChatbot:     def __init__(self, pairs):         self.chat = Chat(pairs, reflections)              def respond(self, user_input):         return self.chat.respond(user_input) 


6. Interacting with the Chatbot

Here we create a function that allows users to interact with the chatbot. It keeps asking for input until the user types "exit".

  • Input Loop: Continuously prompts the user for input and displays the chatbot’s response until "exit" is typed.
Python
def chat_with_bot():     print("Hello, I am your chatbot! Type 'exit' to end the conversation.")     while True:         user_input = input("You: ")         if user_input.lower() == 'exit':             print("Chatbot: Goodbye! Have a nice day!")             break         response = chatbot.respond(user_input)         print(f"Chatbot: {response}") 


7. Initializing the Chatbot

We instantiate the chatbot class and start the chat.

Python
chatbot = RuleBasedChatbot(pairs) chat_with_bot() 

Output:

Screenshot-2025-03-19-125044
Rule Based Chatbot Working

This rule-based chatbot uses a set of predefined patterns to recognize user input and provide responses. While it is limited in flexibility it’s a good starting point for simpler, structured conversations. You can extend this chatbot by adding more complex patterns, integrating machine learning models or incorporating advanced NLP techniques for better accuracy and response handling.


Next Article
Building a Rule-Based Chatbot with Natural Language Processing

Y

ydivyangcju
Improve
Article Tags :
  • NLP
  • AI-ML-DS
  • NLP-Projects
  • AI-ML-DS With Python

Similar Reads

    What is Natural Language Processing (NLP) Chatbots?
    Natural Language Processing (NLP) chatbots are computer programs designed to interact with users in natural language, enabling seamless communication between humans and machines. These chatbots use various NLP techniques to understand, interpret, and generate human language, allowing them to compreh
    12 min read
    The Role of Natural Language Processing (NLP) in Modern Chatbots
    In the digital age, chatbots have emerged as powerful tools for businesses and organizations, transforming the way they interact with customers and streamline operations. At the heart of these chatbots lies Natural Language Processing (NLP), a subfield of artificial intelligence (AI) that focuses on
    7 min read
    Top 7 Applications of NLP (Natural Language Processing)
    In the past, did you ever imagine that you could talk to your phone and get things done? Or that your phone would talk back to you! This has become a pretty normal thing these days with Siri, Alexa, Google Assistant, etc. You can ask any possible questions ranging from “What’s the weather outside” t
    6 min read
    Natural Language Processing in Healthcare
    Due to NLP, clinical documentation has become one of the most important aspects of healthcare. Healthcare systems now process large amounts of data each day, much of which consists of unstructured text, such as clinical notes, reports, and transcriptions. At this stage, Natural Language Processing (
    9 min read
    Best Tools for Natural Language Processing in 2024
    Natural language processing, also known as Natural Language Interface, has recently received a boost over the past several years due to the increasing demands on the ability of machines to understand and analyze human language. Best Tools for Natural Language Processing in 2024This article explores
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences