上面的程序单次结束后,下一次需要手动开始,请重新给我程序
时间: 2024-05-05 07:22:18 浏览: 4
好的,以下是一个简单的 Python 代码,实现了一个类 Chatbot,可以与用户进行简单的对话。你可以根据自己的需求进行修改和拓展。
```python
import random
class Chatbot:
def __init__(self):
self.greetings = ['你好', '您好', 'hi', 'hello']
self.goodbyes = ['再见', '拜拜', 'bye', 'goodbye']
self.questions = ['什么', '为什么', '怎么', '谁', '哪里', '哪些', '多少', '几']
self.responses = {
'你好': ['你好啊', '您好', 'hi', 'hello'],
'再见': ['拜拜', 'bye', 'goodbye'],
'谢谢': ['不用谢', '没问题', '不客气'],
'我爱你': ['我也爱你', '谢谢', '你是个好人'],
'天气': ['今天天气晴朗', '明天可能会下雨', '天气预报说明天会有大雪'],
'笑话': ['为什么狗能够成为人类最好的朋友?因为它们不会告诉别人你的秘密。', '我为什么总是踢床脚板?因为我是踢拳击的出身啊!', '为什么大象不会当演员?因为它太重了,踩坏了舞台。']
}
def chat(self, message):
if message in self.greetings:
return random.choice(self.responses['你好'])
elif message in self.goodbyes:
return random.choice(self.responses['再见'])
elif '?' in message:
return random.choice(self.responses['天气'])
elif '笑话' in message:
return random.choice(self.responses['笑话'])
else:
return "我不理解你在说什么,请换个话题吧。"
if __name__ == '__main__':
bot = Chatbot()
while True:
user_input = input('你说:')
if user_input.lower() == 'exit':
print('再见!')
break
bot_response = bot.chat(user_input)
print('Chatbot说:', bot_response)
```
运行以上代码,即可与 Chatbot 进行简单的对话。你可以调整 self.greetings、self.goodbyes、self.questions 和 self.responses 这些变量,来扩展 Chatbot 的功能和回答。