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 相关文章推荐
使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例
Jan 19 Python
跟老齐学Python之再深点,更懂list
Sep 20 Python
Python进程通信之匿名管道实例讲解
Apr 11 Python
Python中的模块导入和读取键盘输入的方法
Oct 16 Python
在Mac OS系统上安装Python的Pillow库的教程
Nov 20 Python
Python 读写文件和file对象的方法(推荐)
Sep 12 Python
Python 中 Virtualenv 和 pip 的简单用法详解
Aug 18 Python
python逆向入门教程
Jan 15 Python
Python编程中NotImplementedError的使用方法
Apr 21 Python
Django 限制用户访问频率的中间件的实现
Aug 23 Python
20行Python代码实现视频字符化功能
Apr 13 Python
Pycharm导入anaconda环境的教程图解
Jul 31 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+ACCESS 文章管理程序代码
2010/06/21 PHP
PHP SPL标准库之接口(Interface)详解
2015/05/11 PHP
PHP的文件操作与算法实现的面试题示例
2015/08/10 PHP
Yii2中事务的使用实例代码详解
2016/09/07 PHP
详解php语言最牛掰的Laravel框架
2017/11/20 PHP
jquery中实现简单的tabs插件功能的代码
2011/03/02 Javascript
js使用Array.prototype.sort()对数组对象排序的方法
2015/01/28 Javascript
JavaScript正则表达式小结(test|match|search|replace|split|exec)
2016/12/08 Javascript
解决BootStrap Fileinput手机图片上传显示旋转问题
2017/06/01 Javascript
详解Angular2表单-模板驱动的表单(Template-Driven Forms)
2017/08/04 Javascript
angular.js实现列表orderby排序的方法
2018/10/02 Javascript
Javascript 对象(object)合并操作实例分析
2019/07/30 Javascript
p5.js码绘“跳动的小正方形”的实现代码
2019/10/22 Javascript
js获取本日、本周、本月的时间代码
2020/02/01 Javascript
小程序接入腾讯位置服务的详细流程
2020/03/03 Javascript
小程序双头slider选择器的实现示例
2020/03/31 Javascript
如何使用JavaScript检测空闲的浏览器选项卡
2020/05/28 Javascript
浅谈vue中$bus的使用和涉及到的问题
2020/07/28 Javascript
绘制微信小程序验证码功能的实例代码
2021/01/05 Javascript
Python实现的排列组合计算操作示例
2017/10/13 Python
Python编程给numpy矩阵添加一列方法示例
2017/12/04 Python
python使用knn实现特征向量分类
2018/12/26 Python
如何基于线程池提升request模块效率
2020/04/18 Python
学生如何注册Pycharm专业版以及pycharm的安装
2020/09/24 Python
英国最大最好的无人机商店:Drones Direct
2019/07/12 全球购物
购房协议书
2014/04/11 职场文书
小学生操行评语
2014/04/22 职场文书
2014市国税局对照检查材料思想汇报
2014/09/23 职场文书
扬州个园导游词
2015/02/06 职场文书
淘宝客服专员岗位职责
2015/04/07 职场文书
刑事法律意见书
2015/06/04 职场文书
学生会宣传部竞选稿
2015/11/21 职场文书
乡镇团代会开幕词
2016/03/04 职场文书
Java spring定时任务详解
2021/10/05 Java/Android
Spring中的使用@Async异步调用方法
2021/11/01 Java/Android
Python用tkinter实现自定义记事本的方法详解
2022/03/31 Python