如何随机化回复?

2 投票
1 回答
74 浏览
提问于 2025-04-14 16:50

我正在用NLTK在Python中创建一个聊天机器人,但我在考虑把它重写成spaCy。我想找一种方法,让我的AI在回应用户时,可以从一组预先准备好的句子中随机选择。

举个例子;假设机器人说了一些话,用户问“你想讨论这个吗?”我希望它能随机选择“好的,请!”或者“谢谢,不用了!”来回应。

我的代码:

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 个回答

2

使用 random 模块,这是一个标准库(你不需要安装它)。

下面是它的使用方法:

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

撰写回答