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 相关文章推荐
关于Django显示时间你应该知道的一些问题
Dec 25 Python
Python读写docx文件的方法
May 08 Python
python实现名片管理系统
Nov 29 Python
django-rest-framework解析请求参数过程详解
Jul 18 Python
简单了解django缓存方式及配置
Jul 19 Python
Django 开发环境与生产环境的区分详解
Jul 26 Python
python中单下划线(_)和双下划线(__)的特殊用法
Aug 29 Python
通过cmd进入python的步骤
Jun 16 Python
Python如何在bool函数中取值
Sep 21 Python
基于Python实现天天酷跑功能
Jan 06 Python
python 实现网易邮箱邮件阅读和删除的辅助小脚本
Mar 01 Python
Python循环之while无限迭代
Apr 30 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
php 注释规范
2012/03/29 PHP
Erlang的运算符(比较运算符,数值运算符,移位运算符,逻辑运算符)
2012/07/23 PHP
PHP源码分析之变量的存储过程分解
2014/07/03 PHP
php注册系统和使用Xajax即时验证用户名是否被占用
2017/08/31 PHP
为何说PHP引用是个坑,要慎用
2018/04/02 PHP
doctype后如何获得body.clientHeight的方法
2007/07/11 Javascript
Jquery中获取iframe的代码
2011/01/11 Javascript
TimergliderJS 一个基于jQuery的时间轴插件
2011/12/07 Javascript
Uglifyjs(JS代码优化工具)入门 安装使用
2020/04/13 Javascript
JS+CSS实现淡入式焦点图片幻灯切换效果的方法
2015/02/26 Javascript
JavaScript实现仿网易通行证表单验证
2015/05/25 Javascript
基于insertBefore制作简单的循环插空效果
2015/09/21 Javascript
微信小程序switch开关选择器使用详解
2018/01/31 Javascript
详解vue使用插槽分发内容slot的用法
2019/03/28 Javascript
一篇文章介绍redux、react-redux、redux-saga总结
2019/05/23 Javascript
node.JS事件机制与events事件模块的使用方法详解
2020/02/06 Javascript
Vue项目利用axios请求接口下载excel
2020/11/17 Vue.js
使用vue3重构拼图游戏的实现示例
2021/01/25 Vue.js
Python对象类型及其运算方法(详解)
2017/07/05 Python
对numpy Array [: ,] 的取值方法详解
2018/07/02 Python
python中多个装饰器的执行顺序详解
2018/10/08 Python
python 字符串只保留汉字的方法
2018/11/16 Python
Python学习笔记之错误和异常及访问错误消息详解
2019/08/08 Python
PyCharm+PyQt5+QtDesigner配置详解
2020/08/12 Python
python3中确保枚举值代码分析
2020/12/02 Python
CSS3 Columns分列式布局方法简介
2014/05/03 HTML / CSS
HTML5 Geolocation API的正确使用方法
2018/12/04 HTML / CSS
哄娃神器4moms商店:美国婴童用品品牌
2019/03/07 全球购物
英国顶尖手表珠宝品牌独家授权经销商:HS Johnson
2020/10/28 全球购物
大学生村官任职感言
2014/01/09 职场文书
社区禁毒工作方案
2014/06/02 职场文书
人事经理岗位职责范本
2014/08/04 职场文书
课改心得体会范文
2016/01/25 职场文书
怎样写工作总结啊!
2019/06/18 职场文书
赞美教师的句子
2019/09/02 职场文书
pnpm对npm及yarn降维打击详解
2022/08/05 Javascript