🐸

The FAQ Bot

Python 基础python-basics-37-the-faq-bot
奖励: 100 XP
|

初级客服机器人

欢迎来到客户服务中心。

在数字森林里,你可能查阅过魔法书。在 现实世界 (Real World) 中,企业需要瞬间回答成千上万个客户的问题。他们使用 聊天机器人 (Chatbots)

问题:客户总是在问同样的问题(“我的退款在哪里?”,“你们还在营业吗?”)。 目标:构建一个能将 “关键词” 匹配到 “答案” 的机器人。

魔法 vs 现实

真正的聊天机器人通过 input() 监听。

但由于你是在 浏览器模拟环境 中编程,如果我们让脚本等待你打字,整个页面可能会卡住!因此,我们将 模拟 一场对话,通过处理一个预设的消息列表来代替实时打字。

工具箱

# 键 (Key) = 用户问什么, 值 (Value) = 机器人答什么
knowledge = {
  "你好": "你好呀!",
  "再见": "回头见!"
}

print(knowledge["你好"])  # "你好呀!"
# 用遍历列表来模拟 'while True' 接收消息
incoming_messages = ["你好", "退款", "再见"]

for message in incoming_messages:
  if message == "你好":
      print("机器人: 你好!")

你的任务

你正在为 HoppyShop 构建 FAQ 机器人。

系统会给你发送一串客户咨询:queries = ["hours", "refund", "shipping", "joke"]

1
知识库

创建一个名为 responses 的字典。添加这些键值对:

  • "refund" -> "We offer full refunds within 30 days."
  • "hours" -> "We are open 24/7."
  • "shipping" -> "Free shipping on all orders!"
2
模拟

编写一个 for 循环来遍历 queries 列表。

3
回复

在循环内部,检查 message 是否在你的 responses 字典中。

  • 如果 : 打印对应的值。
  • 如果 : 打印 "I don't understand."
参考答案
点击展开
参考答案:

这个模拟证明了你的逻辑是完美的。在真实的 Python 终端里,你只需要把 for 循环换成 while Trueinput() 即可。

queries = ["hours", "refund", "shipping", "joke"]

responses = {
  "refund": "We offer full refunds within 30 days.",
  "hours": "We are open 24/7.",
  "shipping": "Free shipping on all orders!"
}

print("Bot: System Online...")

for message in queries:
  print(f"用户: {message}")
  
  if message in responses:
      print("机器人:", responses[message])
  else:
      print("机器人: I don't understand.")
Loading...
终端输出
Terminal
Ready to run...