如何让Python聊天机器人对两个不同输入返回相同响应?
修复聊天机器人hello/hi匹配问题
问题出在你字典的键定义上:'hello' and 'hi' 在Python中会被解析为逻辑运算,而非同时匹配两个关键词。因为非空字符串在布尔判断中为True,'hello' and 'hi'的结果是最后一个真值'hi',所以你的代码只会匹配到'hi',完全忽略了'hello'。
修改方案
把需要同时匹配的关键词合并成正则选择表达式(用|分隔),让正则引擎能匹配任意一个关键词:
- 将字典中
'hello' and 'hi'的键替换为'hello|hi' - 保持原有的单词边界
\b,避免匹配到包含这些词的其他字符串(比如'helloworld')
修改后的完整代码
import re # 定义关键词与对应回复,用|分隔多个同回复的关键词 keywords_to_responses = { 'hello|hi': 'Hi there! How can I help you?', 'goodbye': 'Goodbye!', 'thank you': 'You\'re welcome! Let me know if you need any more help.', 'how are you': 'I\'m just a chatbot, but I\'m here to help! How can I assist you today?', } def find_matching_response(user_input): for keyword_pattern, response in keywords_to_responses.items(): # 用正则匹配用户输入中的关键词模式 if re.search(r'\b(' + keyword_pattern + r')\b', user_input): return response return 'I\'m sorry, I don\'t understand. Can you please rephrase your question?' def main(): print('Welcome to the Chatbot! (Type "quit" to exit)') while True: user_input = input('You: ').lower() if user_input == 'quit': break response = find_matching_response(user_input) print('Chatbot:', response) if __name__ == '__main__': main()
额外说明
如果后续需要添加更多同回复的关键词(比如'hey'),直接在表达式里追加即可:'hello|hi|hey',无需修改其他逻辑。
内容的提问来源于stack exchange,提问作者Ryan Cheung
相关产品推荐
相关产品推荐

