You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python聊天机器人随机选取预设回复?(NLTK/spaCy场景)

解决NLTK聊天机器人随机回复的问题

你当前用NLTK开发聊天机器人,希望实现从预设多组回复中随机选择一条输出的功能,比如用户问“would you like to discuss that?”时,机器人随机返回“yes please!”或“no thank you!”。你的代码存在几个问题:

  • 单独写if判断处理特定问题会导致重复输出,且逻辑冗余
  • user_input.lower没有调用方法,正确写法是user_input.lower()
  • pairs列表中(.*)的兜底规则放在了what are you doing前面,导致这条特定规则永远不会被匹配到

修复方案

NLTK的Chat类本身就支持随机回复——只要在对应规则的回复列表里放入多个选项,它会自动随机选取。不需要额外写随机逻辑,直接修改pairs列表即可,同时调整规则顺序,并修正退出判断的bug。

修改后的完整代码

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?",
        ["yes please!", "no thank you!"]  # 直接放入多个回复,Chat会随机选择
    ),
    (
        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"what are you doing",
        ["I am talking to you."]
    ),
    (
        r"(.*)",  # 兜底规则放在最后
        ["Hello %1, how can I help you today?"]
    ),
]

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)
        # 修正lower()的调用,统一转为小写后判断
        if user_input.lower() in ["i am satisfied with my care", "quit"]:
            break

chat()

关键修改点

  • 将特定问题的回复列表扩展为多个选项,NLTK的Chat.respond()方法会自动随机选择其中一条返回
  • 调整pairs列表顺序,把(.*)兜底规则移到最后,确保前面的特定规则能被正常匹配
  • 修正退出判断的错误:调用lower()方法,同时增加对"quit"的判断,和规则保持一致
  • 删除了冗余的if判断逻辑,简化代码结构

内容的提问来源于stack exchange,提问作者Danni Kurisu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:55:09