基于用户回答内容进行对话的机器人python代码
时间: 2023-12-20 22:03:44 浏览: 16
以下是一个基于用户回答内容进行对话的简单机器人的 Python 代码示例:
```python
import random
# 定义机器人的回答
responses = {
"hi": ["Hello!", "Hi there!", "Hey!"],
"how are you": ["I am doing well, thank you.", "Not too bad, thanks for asking.", "I am great! How about you?"],
"what's your name": ["My name is Bot.", "I am Bot, nice to meet you!"],
"default": ["Sorry, I did not understand what you said.", "Can you please rephrase that?", "I am not sure what you mean."]
}
# 定义机器人的主函数
def chatbot():
print("Hello! I am a simple chatbot. How can I help you today?")
while True:
user_input = input().lower()
if user_input in responses:
bot_response = random.choice(responses[user_input])
print(bot_response)
else:
bot_response = random.choice(responses["default"])
print(bot_response)
# 运行机器人
chatbot()
```
上述代码中,我们首先定义了一个 `responses` 字典,其中包含了机器人对不同用户回答的回应。然后我们定义了一个 `chatbot` 函数,它会在运行时打印问候语,并等待用户输入。在用户输入后,我们检查其是否匹配了我们提前定义的某个回答,如果匹配,则随机从对应的回答列表中选择一个回答并输出;如果不匹配,则随机从默认回答列表中选择一个回答并输出。最后,我们调用 `chatbot` 函数以启动机器人程序。
请注意,上述代码只是一个简单的示例,实际中可能需要更复杂的逻辑以及更多的回答选项来提高机器人的智能程度和回答准确率。