Python如何实现机器人聊天


Posted in Python onSeptember 10, 2020

今天午休的时候,无意之中看了一篇博客,名字叫Python实现机器人,感觉挺有的意思的。
于是用其写了一个简单的Python聊天,源码如下所示:

# -*- coding: utf-8 -*-
import aiml
import sys
import os
 
 
def get_module_dir(name):
 print("module", sys.modules[name])
 path = getattr(sys.modules[name], '__file__', None)
 print(path)
 if not path:
 raise AttributeError('module %s has not attribute __file__' % name)
 return os.path.dirname(os.path.abspath(path))
 
 
alice_path = get_module_dir('aiml') + '\\botdata\\alice'
 
os.chdir(alice_path) # 切换到语料库所在工作目录
 
alice = aiml.Kernel() # 创建机器人alice对象
alice.learn("startup.xml") # 加载...\\botdata\\alice\\startup.xml
alice.respond('LOAD ALICE') # 加载...\\botdata\\alice目录下的语料库
 
while True:
 message = input("Enter your message >> ")
 if("exit" == message):
 exit()
 response = alice.respond(message) # 机器人应答
 print(response)

注意:如果出现某某模块找不到的时候,记得使用pip安装对应的模块。

效果图如下所示:

Python如何实现机器人聊天

唯一美中不足的是英文,不过没关系,国内有图灵机器人。

代码如下所示:

from urllib.request import urlopen,Request
from urllib.error import URLError
from urllib.parse import urlencode
import json

class TuringChatMode(object):
  """this mode base on turing robot"""

  def __init__(self):
    # API接口地址
    self.turing_url = 'http://www.tuling123.com/openapi/api?'

  def get_turing_text(self,text):
    ''' 请求方式:  HTTP POST
      请求参数:  参数   是否必须    长度     说明
            key    必须     32      APIkey
            info    必须     1-32     请求内容,编码方式为"utf-8"
            userid   必须     32      MAC地址或ID
    '''
    turing_url_data = dict(
      key = 'fcbf9efe277e493993e889eabca5b331',
      info = text,
      userid = '60-14-B3-BA-E1-4D',

    )
    # print("The things to Request is:",self.turing_url + urlencode(turing_url_data))
    self.request = Request(self.turing_url + urlencode(turing_url_data))
    # print("The result of Request is:",self.request)

    try:
      w_data = urlopen(self.request)
      # print("Type of the data from urlopen:",type(w_data))
      # print("The data from urlopen is:",w_data)
    except URLError:
      raise IndexError("No internet connection available to transfer txt data")
      # 如果发生网络错误,断言提示没有可用的网络连接来传输文本信息
    except:
      raise KeyError("Server wouldn't respond (invalid key or quota has been maxed out)")
      # 其他情况断言提示服务相应次数已经达到上限

    response_text = w_data.read().decode('utf-8')
    # print("Type of the response_text :",type(response_text))
    # print("response_text :",response_text)

    json_result = json.loads(response_text)
    # print("Type of the json_result :",type(json_result))
    return json_result['text']

if __name__ == '__main__':
  print("Now u can type in something & input q to quit")

  turing = TuringChatMode()

  while True:
    msg = input("\nMaster:")
    if msg == 'q':
      exit("u r quit the chat !")     # 设定输入q,退出聊天。
    else:
      turing_data = turing.get_turing_text(msg)
      print("Robot:",turing_data)

效果图如下:

Python如何实现机器人聊天

可能由于机器人智能太低了,有点答非所问。

更多精彩可以去图灵机器人官网了解:http://www.tuling123.com

编程的世界是有趣的,你去探索,你会发现很多有意思的事情。

以上就是Python如何实现机器人聊天的详细内容,更多关于python 实现机器人聊天的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Linux下Python获取IP地址的代码
Nov 30 Python
在Python中使用SQLite的简单教程
Apr 29 Python
Django 生成登陆验证码代码分享
Dec 12 Python
Python设计模式之中介模式简单示例
Jan 09 Python
Python pyinotify日志监控系统处理日志的方法
Mar 08 Python
python如何查看微信消息撤回
Nov 27 Python
CentOS下Python3的安装及创建虚拟环境的方法
Nov 28 Python
python实现图像检索的三种(直方图/OpenCV/哈希法)
Aug 08 Python
python 调试冷知识(小结)
Nov 11 Python
tensorflow模型的save与restore,及checkpoint中读取变量方式
May 26 Python
解决Alexnet训练模型在每个epoch中准确率和loss都会一升一降问题
Jun 17 Python
pytorch中F.avg_pool1d()和F.avg_pool2d()的使用操作
May 22 Python
Python 必须了解的5种高级特征
Sep 10 #Python
matplotlib 多个图像共用一个colorbar的实现示例
Sep 10 #Python
利用python 读写csv文件
Sep 10 #Python
如何用Python 加密文件
Sep 10 #Python
Python 高效编程技巧分享
Sep 10 #Python
python操作redis数据库的三种方法
Sep 10 #Python
Python计算矩阵的和积的实例详解
Sep 10 #Python
You might like
搜索和替换文件或目录的一个好类--很实用
2006/10/09 PHP
用PHP实现的四则运算表达式计算实现代码
2011/08/02 PHP
PHP 获取文件路径(灵活应用__FILE__)
2013/02/15 PHP
php生成不重复随机数、数组的4种方法分享
2015/03/30 PHP
一个完整的php文件上传类实例讲解
2015/10/27 PHP
jQuery 使用手册(六)
2009/09/23 Javascript
基于PHP+Jquery制作的可编辑的表格的代码
2011/04/10 Javascript
JS清除IE浏览器缓存的方法
2013/07/26 Javascript
window.location的重写及判断location是否被重写
2014/09/04 Javascript
浅谈javascript中replace()方法
2015/11/10 Javascript
谈谈对offsetleft兼容性的理解
2015/11/11 Javascript
从零开始学习Node.js系列教程之SQLite3和MongoDB用法分析
2017/04/13 Javascript
vue-router路由懒加载和权限控制详解
2017/12/13 Javascript
生产制造追溯系统之再说条码打印
2019/06/03 Javascript
layui+jquery支持IE8的表格分页方法
2019/09/28 jQuery
浅谈Vue2.4.0 $attrs与inheritAttrs的具体使用
2020/03/08 Javascript
vue中的双向数据绑定原理与常见操作技巧详解
2020/03/16 Javascript
简述Python中的进程、线程、协程
2016/03/18 Python
Python实现的IP端口扫描工具类示例
2019/02/15 Python
python实现五子棋游戏
2019/06/18 Python
Django DRF APIView源码运行流程详解
2020/08/17 Python
关于iframe跨域使用postMessage的实现
2019/10/29 HTML / CSS
英国精品买手店:Browns Fashion
2016/09/29 全球购物
Expedia印度尼西亚站:预订酒店、廉价航班和度假套餐
2018/01/31 全球购物
Canal官网:巴西女性时尚品牌
2019/10/16 全球购物
如何保障Web服务器安全
2014/05/05 面试题
一套比较完整的软件测试人员面试题
2012/05/13 面试题
艺术应用与设计个人的自我评价
2013/11/23 职场文书
高中生家长寄语大全
2014/04/03 职场文书
网页美工求职信范文
2014/04/17 职场文书
2014年端午节演讲稿范文
2014/05/23 职场文书
行政助理岗位职责
2015/02/10 职场文书
2015年保送生自荐信
2015/03/24 职场文书
银行催款通知书
2015/04/17 职场文书
实施意见格式范本
2015/06/05 职场文书
职业生涯规划书之大学四年
2019/08/07 职场文书