如何终止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.")
关键说明
- 替换默认循环:放弃
chat.converse(),自己实现会话循环,这样可以完全控制终止条件。 - 不区分大小写匹配:将用户输入转为小写,确保输入"Thanks"、"THANKS"等变体也能触发终止。
- 先回复再终止:机器人会先输出"you're welcome",再执行
break停止循环,符合需求。 - 修正拼写错误:原代码中的
avalable改为正确的available,避免回复内容出错。
内容的提问来源于stack exchange,提问作者Ziad Walid
相关产品推荐
相关产品推荐

