EN VI

Python - How do I randomise responses?

2024-03-12 01:30:05
Python - How do I randomise responses?

I am using NLTK to create a chatbot in Python but I am considering rewriting it for spaCy. I am looking for a way to feed my AI several pre built sentences to choose from at random from the pairs when responding to a user.

For example; say the bot says something and the user asks “would you like to discuss that?” I want it to choose between “yes please!” and “no thank you!” at random.

My code:

import nltk
from nltk.chat.util import Chat, reflections
nltk.download("punkt")


pairs = [

 (
     r"I am satisfied with my care|quit",
     ["Bye, take care. See you soon!"]
 ),
 (
     r"hi|hello",
     ["Hello what is your name?", ]
 ),
 (
     r"my name is (.*)",
     ["Hello %1, how can I help you today?", ]
 ),
 (
     r"what is your name?",
     ["My name is ZeroBot and I'm here to help you.", ]
 ),
 (
     r"how are you?",
     ["I'm doing well, thank you!", ]
 ),
 (
     r"sorry (.*)",
     ["It's alright, no problem.", ]
 ),
 (
     r"(.*)",
     ["Hello %1, how can I help you today?", ]
 ),
 (
     r"what are you doing",
     ["I am talking to you.", ]
 ),
 (
     r"would you like to discuss that?",
     ["no Thank you.", ]
 ),
]


chatbot = Chat(pairs, reflections)


def chat():
 print("Hi, I'm ZeroBot. How can I help you today? Type 'I am satisfied with my care' to exit.")
 while True:
     user_input = input("You: ")
     response = chatbot.respond(user_input)
     print("ZeroBot:", response)
     if user_input.lower == "I am satisfied with my care":
         break


chat()

Solution:

Use the random module, which is a standard library (you don't have to install it). Here is how to use it:

import random
if (your if statement):
    random_value = random.randint(1, 2)
    match random_value:
        case 1:
            print(“yes please!”)
        case 2:
            print(“no thank you!”)

PS: avoid downvoting for no reason. If you downvote, please comment why.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login