基于Python-ChatterBot搭建不同adapter的聊天机器人(使用NB进行场景分类)

chatterbot是一款python接口的,基于一系列规则和机器学习算法完成的聊天机器人。具有结构清晰,可扩展性好,简单实用的特点。本文通过chatterbot 的不同adapter来介绍如何构建自己的聊天机器人,关与chatterbot详细资料请请阅读源码,纯Python写的,阅读性比较强。好啦,我就直接上代码了。PS:现在正在收集语料库,过段时间更新基于深度循环网络LSTM的带有记忆的ChatBot。

安装

是的,安装超级简单(Ubuntu),用pip就可以啦~

sudo pip install chatterbot


各式各样的Adapter

大家已经知道chatterbot的聊天逻辑和输入输出以及存储,是由各种adapter来限定的,我们先看看流程图,一会软再一起看点例子,看看怎么用。

基础版本

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2. from chatterbot import ChatBot  
  3. # 构建ChatBot并指定  
  4. Adapterbot = ChatBot(  
  5.    'Default Response Example Bot',  
  6.      storage_adapter='chatterbot.storage.JsonFileStorageAdapter',  
  7.    logic_adapters=[  
  8.        {  
  9.            'import_path''chatterbot.logic.BestMatch'  
  10.        },  
  11.        {  
  12.            'import_path''chatterbot.logic.LowConfidenceAdapter',  
  13.            'threshold'0.65,  
  14.            'default_response''I am sorry, but I do not understand.'  
  15.        }  
  16.    ],  
  17.    trainer='chatterbot.trainers.ListTrainer')  
  18. # 手动给定一点语料用于训练  
  19. bot.train([  
  20.    'How can I help you?',  
  21.    'I want to create a chat bot',  
  22.    'Have you read the documentation?',  
  23.    'No, I have not',  
  24.    'This should help get you started: http://chatterbot.rtfd.org/en/latest/quickstart.html'])  
  25. # 给定问题并取回结果  
  26. question = 'How do I make an omelette?'  
  27. print(question)  
  28. response = bot.get_response(question)  
  29. print(response)  
  30. print("\n")  
  31. question = 'how to make a chat bot?'  
  32. print(question)  
  33. response = bot.get_response(question)  
  34. print(response)  

对话内容如下:

How do I make an omelette?
I am sorry, but I do not understand.
how to make a chat bot?
Have you read the documentation?


处理时间和数学计算的Adapter

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2. from chatterbot import ChatBot  
  3. bot = ChatBot(  
  4.    "Math & Time Bot",  
  5.    logic_adapters=[  
  6.        "chatterbot.logic.MathematicalEvaluation",  
  7.        "chatterbot.logic.TimeLogicAdapter"  
  8.    ],  input_adapter="chatterbot.input.VariableInputTypeAdapter",  
  9.    output_adapter="chatterbot.output.OutputAdapter")  
  10. # 进行数学计算  
  11. question = "What is 4 + 9?"  
  12. print(question)response = bot.get_response(question)  
  13. print(response)  
  14. print("\n")  
  15. # 回答和时间相关的问题  
  16. question = "What time is it?"  
  17. print(question)  
  18. response = bot.get_response(question)  
  19. print(response)  

对话如下:

What is 4 + 9?
( 4 + 9 ) = 13


What time is it?
The current time is 05:08 PM


导出语料到json文件

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2. from chatterbot import ChatBot  
  3. '''''如果一个已经训练好的chatbot,你想取出它的语料,用于别的chatbot构建,可以这么做'''  
  4. chatbot = ChatBot(  
  5.    'Export Example Bot',  
  6.  trainer='chatterbot.trainers.ChatterBotCorpusTrainer')  
  7. # 训练一下咯  
  8. chatbot.train('chatterbot.corpus.english')  
  9. # 把语料导出到json文件中chatbot.trainer.export_for_training('./my_export.json')  


反馈式学习聊天机器人

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2. from chatterbot import ChatBot  
  3. import logging  
  4. """反馈式的聊天机器人,会根据你的反馈进行学习"""  
  5. # 把下面这行前的注释去掉,可以把一些信息写入日志中  
  6. # logging.basicConfig(level=logging.INFO)  
  7. # 创建一个聊天机器人  
  8. bot = ChatBot(  
  9.    'Feedback Learning Bot',  
  10.    storage_adapter='chatterbot.storage.JsonFileStorageAdapter',  
  11.    logic_adapters=[  
  12.        'chatterbot.logic.BestMatch'  
  13.    ],  
  14.    input_adapter='chatterbot.input.TerminalAdapter',  
  15.  output_adapter='chatterbot.output.TerminalAdapter')  
  16. DEFAULT_SESSION_ID = bot.default_session.id  
  17. def get_feedback():  
  18.    from chatterbot.utils import input_function  
  19.    text = input_function()  
  20.    if 'Yes' in text:  
  21.        return True  
  22.    elif 'No' in text:  
  23.        return False  
  24.    else:  
  25.        print('Please type either "Yes" or "No"')  
  26.        return get_feedback()  
  27. print('Type something to begin...')  
  28. # 每次用户有输入内容,这个循环就会开始执行  
  29. while True:  
  30.    try:  
  31.        input_statement = bot.input.process_input_statement()  
  32.        statement, response = bot.generate_response(input_statement, DEFAULT_SESSION_ID)  
  33.        print('\n Is "{}" this a coherent response to "{}"? \n'.format(response, input_statement))  
  34.        if get_feedback():  
  35.            bot.learn_response(response,input_statement)  
  36.        bot.output.process_response(response)  
  37.        # 更新chatbot的历史聊天数据  
  38.        bot.conversation_sessions.update(  
  39.            bot.default_session.id_string,  
  40.            (statement, response, )  
  41.        )  
  42.    # 直到按ctrl-c 或者 ctrl-d 才会退出  
  43.    except (KeyboardInterrupt, EOFError, SystemExit):  
  44.        break  
  45. 反馈式学习聊天机器人  
  46.   
  47. 使用Ubuntu数据集构建聊天机器人  
  48.   
  49. from chatterbot import ChatBot  
  50. import logging  
  51. '''''这是一个使用Ubuntu语料构建聊天机器人的例子'''  
  52. # 允许打日志logging.basicConfig(level=logging.INFO)  
  53. chatbot = ChatBot(  
  54.    'Example Bot',   trainer='chatterbot.trainers.UbuntuCorpusTrainer')  
  55. # 使用Ubuntu数据集开始训练  
  56. chatbot.train()  
  57. # 我们来看看训练后的机器人的应答  
  58. response = chatbot.get_response('How are you doing today?')  
  59. print(response)  


借助微软的聊天机器人

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2. from chatterbot import ChatBot  
  3. from settings import Microsoft  
  4. '''''关于获取微软的user access token请参考以下的文档https://docs.botframework.com/en-us/restapi/directline/'''  
  5. chatbot = ChatBot(  
  6.    'MicrosoftBot',  
  7.    directline_host = Microsoft['directline_host'],  
  8.    direct_line_token_or_secret = Microsoft['direct_line_token_or_secret'],  
  9.    conversation_id = Microsoft['conversation_id'],  
  10.    input_adapter='chatterbot.input.Microsoft',  
  11.    output_adapter='chatterbot.output.Microsoft',  
  12.    trainer='chatterbot.trainers.ChatterBotCorpusTrainer')chatbot.train('chatterbot.corpus.english')  
  13. # 是的,会一直聊下去  
  14. while True:  
  15.    try:  
  16.        response = chatbot.get_response(None)  
  17.   
  18.    # 直到按ctrl-c 或者 ctrl-d 才会退出  
  19.    except (KeyboardInterrupt, EOFError, SystemExit):  
  20.        break  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值