上一篇(安装):https://www.cnblogs.com/Ctrl-cCtrl-v/p/13220584.html
基础代码:
1 from chatterbot import ChatBot 2 from chatterbot.trainers import ListTrainer 3 4 chatbot = ChatBot("小土豆", 5 trainer='chatterbot.trainers.ListTrainer', 6 ) 7 8 9 10 conversation = [ 11 "你好", 12 "Hi~", 13 "你好啊!" 14 ] 15 chatbot.train(conversation) 16 17 conversation = [ 18 "你好吗?", 19 "我很好,谢谢!" 20 ] 21 chatbot.train(conversation) 22 23 conversation = [ 24 "你叫什么名字?", 25 "我叫小土豆" 26 27 ] 28 chatbot.train(conversation) 29 30 conversation = [ 31 "你过得怎么样?", 32 "我很好,谢谢!" 33 ] 34 chatbot.train(conversation) 35 36 conversation = [ 37 "哈哈", 38 "呵呵", 39 "呵呵哒" 40 ] 41 chatbot.train(conversation) 42 43 44 while True: 45 h=input("话:") 46 response = chatbot.get_response(h) 47 print(response)
小土豆是机器人名字没啥用
conversation列表是训练的话,一问一答
默认使用的Levenshtein distance算法能让引擎从问答对中选出一个相近的回答
你还可以在第4行代码上加上
1 logic_adapters=[ 2 { 3 'import_path': 'chatterbot.logic.BestMatch' 4 }, 5 { 6 'import_path': 'chatterbot.logic.LowConfidenceAdapter', 7 'threshold': 0.65, #匹配度 8 'default_response': 'I am sorry, but I do not understand.' #低于匹配度默认回答 9 } 10 ] 11 12 read_only=True #不学习用户输入的东西,建议关闭,他会乱学习,效果不好!
最终高级版:
1 from chatterbot import ChatBot 2 from chatterbot.trainers import ListTrainer 3 4 chatbot = ChatBot("小土豆", 5 trainer='chatterbot.trainers.ListTrainer', 6 read_only=True, 7 logic_adapters=[ 8 { 9 "import_path": 'chatterbot.logic.BestMatch'#回话逻辑 10 11 }, 12 13 { 14 'import_path': 'chatterbot.logic.LowConfidenceAdapter',#回话逻辑 15 'threshold': 0.65,#低于置信度,则默认回答 16 'default_response': '我还是个小孩子,不知道怎么回答' 17 }] 18 ) 19 20 21 22 conversation = [ 23 "你好", 24 "Hi~", 25 "你好啊!" 26 ] 27 chatbot.train(conversation) 28 29 conversation = [ 30 "你好吗?", 31 "我很好,谢谢!" 32 ] 33 chatbot.train(conversation) 34 35 conversation = [ 36 "你叫什么名字?", 37 "我叫小土豆" 38 39 ] 40 chatbot.train(conversation) 41 42 conversation = [ 43 "你过得怎么样?", 44 "我很好,谢谢!" 45 ] 46 chatbot.train(conversation) 47 48 conversation = [ 49 "哈哈", 50 "呵呵", 51 "呵呵哒" 52 ] 53 chatbot.train(conversation) 54 55 56 while True: 57 h=input("话:") 58 response = chatbot.get_response(h) 59 print(response)