How do I randomize responses?

76 views Asked by At

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
import random
nltk.download("punkt")


pairs = [

 (
     r"I am satisfied with my care|quit",
     ["Bye, take care. See you soon!"]
 ),
 (
     r"would you like to discuss that?",
     ["no Thank you.", ]
 ),
 (
     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.", ]
 ),

]


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
 
     if user_input.lower == "would you like to discuss that?":
         random_value = random.randint(1, 2)
         match random_value:
             case 1:
                 print("yes please!")
             case 2:
                 print("no thank you!")


chat()
1

There are 1 answers

20
Qualcuno2 On

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!”)