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

如何终止NLTK聊天机器人?实现输入‘thanks’后停止运行

解决NLTK聊天机器人输入"thanks"后停止运行的问题

要实现输入"thanks"后机器人回复并停止运行,你需要替换默认的converse()方法,自定义会话循环来控制终止条件——因为默认的converse()只会在输入quit/bye等默认退出词时停止,无法直接绑定"thanks"作为终止触发词。

修改后的完整代码

from nltk.chat.util import Chat, reflections

words =[
        ['(hi|hey|hola|goodmorning|hay)', ['hello, how can i help you?']],
        ['(order|can i order)', ['what size']],
        ['(my size is (.*))', ['%1 is available, what color?']],
        ['(my color is (.*))', ['%1 is available']],
        ['(how much)', ['price is 300le, send your information']],
        ['(my information is)', ['order placed and will be delivered in 3 working days']],
        ['(thanks)', ["you're welcome"]],
       ]
        
chat = Chat(words, reflections) 

# 自定义会话循环,控制终止逻辑
while True:
    user_input = input("You: ")
    processed_input = user_input.lower()
    response = chat.respond(processed_input)
    
    if response:
        print("Bot:", response)
        # 当输入包含thanks时,终止循环
        if 'thanks' in processed_input:
            break
    else:
        print("Bot: I don't understand that.")

关键说明

  1. 替换默认循环:放弃chat.converse(),自己实现会话循环,这样可以完全控制终止条件。
  2. 不区分大小写匹配:将用户输入转为小写,确保输入"Thanks"、"THANKS"等变体也能触发终止。
  3. 先回复再终止:机器人会先输出"you're welcome",再执行break停止循环,符合需求。
  4. 修正拼写错误:原代码中的avalable改为正确的available,避免回复内容出错。

内容的提问来源于stack exchange,提问作者Ziad Walid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:35:19