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 相关文章推荐
用python实现的可以拷贝或剪切一个文件列表中的所有文件
Apr 30 Python
Python中的exec、eval使用实例
Sep 23 Python
Python Web框架Flask中使用七牛云存储实例
Feb 08 Python
python中字典dict常用操作方法实例总结
Apr 04 Python
python开发简易版在线音乐播放器
Mar 03 Python
django实现前后台交互实例
Aug 07 Python
Python 异常处理的实例详解
Sep 11 Python
对Python生成器、装饰器、递归的使用详解
Jul 19 Python
django框架模型层功能、组成与用法分析
Jul 30 Python
python能做什么 python的含义
Oct 12 Python
flask框架url与重定向操作实例详解
Jan 25 Python
python爬虫爬取图片的简单代码
Jan 18 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
这部番真是良心,画质好到像风景区,剧情让人跟着小公会热血沸腾
2020/03/10 日漫
php打乱数组二维数组多维数组的简单实例
2016/06/17 PHP
golang实现php里的serialize()和unserialize()序列和反序列方法详解
2018/10/30 PHP
PHP实现文件上传与下载
2020/08/28 PHP
js实现拉伸拖动iframe的具体代码
2013/08/03 Javascript
ie7+背景透明文字不透明超级简单的实现方法
2014/01/17 Javascript
js实现的GridView即表头固定表体有滚动条且可滚动
2014/02/19 Javascript
jquery的each方法使用示例分享
2014/03/25 Javascript
js获取select默认选中的Option并不是当前选中值
2014/05/07 Javascript
jquery+easeing实现仿flash的载入动画
2015/03/10 Javascript
javascript事件委托的用法及其好处简析
2016/04/04 Javascript
详解vue.js移动端导航navigationbar的封装
2017/07/05 Javascript
vue.js的手脚架vue-cli项目搭建的步骤
2017/08/30 Javascript
jfinal与bootstrap的登出实战详解
2017/11/27 Javascript
微信小程序中实现手指缩放图片的示例代码
2018/03/13 Javascript
vue component 中引入less文件报错 Module build failed
2019/04/17 Javascript
JQuery获取元素尺寸、位置及页面滚动事件应用示例
2019/05/14 jQuery
JS实现百度搜索框
2021/02/25 Javascript
[03:00]《DAC最前线》之欧美新秀VS老将
2015/02/01 DOTA
新手如何快速入门Python(菜鸟必看篇)
2017/06/10 Python
Pycharm技巧之代码跳转该如何回退
2017/07/16 Python
使用python实现快速搭建简易的FTP服务器
2018/09/12 Python
selenium在执行phantomjs的API并获取执行结果的方法
2018/12/17 Python
pytorch 自定义卷积核进行卷积操作方式
2019/12/30 Python
详解css3中的伪类before和after常见用法
2020/11/17 HTML / CSS
HTML5实现移动端弹幕动画效果
2019/08/01 HTML / CSS
EQVVS官网:设计师男装和女装
2018/10/24 全球购物
哥伦比亚加拿大官网:Columbia Sportswear Canada
2020/09/07 全球购物
医学毕业生自我鉴定
2013/10/30 职场文书
五年级数学教学反思
2014/02/11 职场文书
行政部经理助理岗位职责
2014/06/15 职场文书
纪念九一八事变演讲稿:勿忘国耻
2014/09/14 职场文书
交通事故赔偿协议书
2014/10/16 职场文书
地陪导游欢迎词
2015/01/26 职场文书
省级三好学生主要事迹材料
2015/11/03 职场文书
python的列表生成式,生成器和generator对象你了解吗
2022/03/16 Python