w3resource

Building a Rule-Based Chatbot with Python and Regular Expressions

Write a Python program to develop a rule-based chatbot using regular expressions.

Developing a rule-based chatbot using regular expressions involves creating a conversational agent that responds to user inputs based on predefined patterns and rules defined using regular expressions. By matching input text against these patterns, the chatbot can identify user intents and provide appropriate responses. Regular expressions allow for flexible and efficient pattern matching, enabling the chatbot to handle various types of user queries and interactions effectively.

Sample Solution:

Python Code :

# Import the re module for regular expressions
import re

# Define patterns and responses
# Create a dictionary where keys are regex patterns and values are responses
patterns_responses = {
    r'hi|hello|hey': 'Hello! How can I assist you today?',
    r'how are you': 'I am just a bot, but I am doing great! How about you?',
    r'what is your name': 'I am a chatbot created to assist you with your questions.',
    r'(.*) your (favorite|favourite) (.*)': 'I do not have preferences, but I enjoy helping you!',
    r'thank you|thanks': 'You are welcome! If you have more questions, feel free to ask.',
    r'bye|goodbye': 'Goodbye! Have a great day!'
}

# Default response for unmatched patterns
# Set a default response for when no pattern matches the user input
default_response = "I'm sorry, I don't understand that. Can you please rephrase?"

# Function to match user input to a pattern and return the corresponding response
def get_response(user_input):
    # Iterate over the dictionary of patterns and responses
    for pattern, response in patterns_responses.items():
        # Check if the user input matches the current pattern (case-insensitive)
        if re.search(pattern, user_input, re.IGNORECASE):
            # If a match is found, return the corresponding response
            return response
    # If no match is found, return the default response
    return default_response

# Main function to run the chatbot
def chatbot():
    # Print an initial greeting message
    print("Chatbot: Hi! I am your rule-based chatbot. Type 'bye' to exit.")
    while True:
        # Read user input
        user_input = input("You: ")
        # Check if the user wants to exit the chat
        if re.search(r'bye|goodbye', user_input, re.IGNORECASE):
            # Print a farewell message and break the loop to exit
            print("Chatbot: Goodbye! Have a great day!")
            break
        # Get the response based on user input
        response = get_response(user_input)
        # Print the chatbot's response
        print(f"Chatbot: {response}")

# Run the chatbot
if __name__ == '__main__':
    # Call the chatbot function to start the interaction
    chatbot()

Output:

runfile('C:/Users/ME/untitled1.py', wdir='C:/Users/ME')
Chatbot: Hi! I am your rule-based chatbot. Type 'bye' to exit.
You: Hello
Chatbot: Hello! How can I assist you today?
You: Can you tell me why is the sky blue?
Chatbot: I'm sorry, I don't understand that. Can you please rephrase?
You: You have any preference!
Chatbot: I'm sorry, I don't understand that. Can you please rephrase?
You: ok, bye.
Chatbot: Goodbye! Have a great day!

Explanation:

  • Imports:
  • The "re" module is imported to use regular expressions for pattern matching.
  • Patterns and Responses:
  • A dictionary 'patterns_responses' is created where each key is a regex pattern and the corresponding value is the response the chatbot should give if the pattern matches the user input.
  • Patterns are designed to match common greetings, questions, and farewells.
  • Default Response:
  • A default response is defined to handle cases where the user input doesn't match any predefined pattern.
  • get_response Function:
  • This function takes user input, iterates over the 'patterns_responses' dictionary, and checks if the input matches any pattern using regex.
  • If a match is found, it returns the corresponding response; otherwise, it returns the default response.
  • chatbot Function:
  • This function runs the chatbot, starting with a greeting message.
  • It enters a loop where it reads user input and checks if the user wants to exit by matching input against "bye" or "goodbye".
  • For other inputs, it calls 'get_response' to determine the appropriate response and prints it.
  • The loop continues until the user indicates they want to exit.
  • Main Execution:
  • If the script is run directly, it calls the "chatbot()" function to start the interaction.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Monitor and Alert System Resource usage with Python.
Next: Versioned Datasets Management System with Python

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.