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中的死锁、可重入锁和互斥锁
Nov 05 Python
利用python画一颗心的方法示例
Jan 31 Python
Python分析学校四六级过关情况
Nov 22 Python
python数字图像处理实现直方图与均衡化
May 04 Python
python遍历小写英文字母的方法
Jan 02 Python
Python3 执行系统命令并获取实时回显功能
Jul 09 Python
Django Channels 实现点对点实时聊天和消息推送功能
Jul 17 Python
Python 窗体(tkinter)下拉列表框(Combobox)实例
Mar 04 Python
python 中不同包 类 方法 之间的调用详解
Mar 09 Python
Python爬虫实例——scrapy框架爬取拉勾网招聘信息
Jul 14 Python
python 标准库原理与用法详解之os.path篇
Oct 24 Python
python实现手机推送 代码也就10行左右
Apr 12 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中模拟处理HTTP PUT请求的例子
2014/07/22 PHP
ThinkPHP登录功能的实现方法
2014/08/20 PHP
php有效防止图片盗用、盗链的两种方法
2016/11/01 PHP
JavaScript 动态创建VML的方法
2009/10/14 Javascript
javascript中常用编程知识
2013/04/08 Javascript
js 控制图片大小核心讲解
2013/10/09 Javascript
上传图片预览JS脚本 Input file图片预览的实现示例
2014/10/23 Javascript
jQuery实现页面滚动时动态加载内容的方法
2015/03/20 Javascript
js实现改进的仿蓝色论坛导航菜单效果代码
2015/09/06 Javascript
js 右侧浮动层效果实现代码(跟随滚动)
2015/11/22 Javascript
js实现文字滚动效果
2016/03/03 Javascript
详解JS正则replace的使用方法
2016/03/06 Javascript
Winform客户端向web地址传参接收参数的方法
2016/05/17 Javascript
用原生JS对AJAX做简单封装的实例代码
2016/07/13 Javascript
javascript入门之数组[新手必看]
2016/11/21 Javascript
详解angularJs中自定义directive的数据交互
2017/01/13 Javascript
浅谈react前后端同构渲染
2017/09/20 Javascript
vue bus全局事件中心简单Demo详解
2018/02/26 Javascript
如何安装控制器JavaScript生成插件详解
2018/10/21 Javascript
TypeScript 引用资源文件后提示找不到的异常处理技巧
2020/07/15 Javascript
在Python的Flask框架中实现单元测试的教程
2015/04/20 Python
简单讲解Python中的字符串与字符串的输入输出
2016/03/13 Python
Python实现ssh批量登录并执行命令
2016/10/25 Python
Python基于Socket实现的简单聊天程序示例
2017/08/05 Python
Python实现XML文件解析的示例代码
2018/02/05 Python
详解如何在python中读写和存储matlab的数据文件(*.mat)
2018/02/24 Python
Python使用cx_Oracle模块操作Oracle数据库详解
2018/05/07 Python
Ubuntu18.04下python版本完美切换的解决方法
2019/06/14 Python
python基于Kivy写一个图形桌面时钟程序
2021/01/28 Python
应届生护士求职信
2013/11/01 职场文书
毕业生实习鉴定
2013/12/11 职场文书
采购部部长岗位职责
2014/02/06 职场文书
会计自荐信范文
2014/03/09 职场文书
村主任个人对照检查材料
2014/10/01 职场文书
2015年班干部工作总结
2015/04/29 职场文书
Go 语言下基于Redis分布式锁的实现方式
2021/06/28 Golang