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中移动目录结构的方法
Jan 31 Python
Python中的数据对象持久化存储模块pickle的使用示例
Mar 03 Python
asyncio 的 coroutine对象 与 Future对象使用指南
Sep 11 Python
浅析Python函数式编程
Oct 06 Python
pygame游戏之旅 按钮上添加文字的方法
Nov 21 Python
Django Celery异步任务队列的实现
Jul 24 Python
使用Python的networkx绘制精美网络图教程
Nov 21 Python
np.random.seed() 的使用详解
Jan 14 Python
Python简单实现区域生长方式
Jan 16 Python
Python获取、格式化当前时间日期的方法
Feb 10 Python
python生成xml时规定dtd实例方法
Sep 21 Python
Django项目如何正确配置日志(logging)
Apr 29 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 PDO中文乱码解决办法
2009/07/20 PHP
探讨:如何使用PHP实现计算两个日期间隔的年、月、周、日数
2013/06/13 PHP
PHP中isset与array_key_exists的区别实例分析
2015/06/02 PHP
php实现XML和数组的相互转化功能示例
2017/02/08 PHP
jQuery each()方法的使用方法
2010/03/18 Javascript
JavaScript Perfection kill 测试及答案
2010/03/23 Javascript
jQuery中end()方法用法实例
2015/01/08 Javascript
基于javascript编写简单日历
2016/05/02 Javascript
JSP基于Bootstrap分页显示实例解析
2016/06/12 Javascript
利用yarn实现一个webpack+react种子
2016/10/25 Javascript
微信小程序  自定义创建详细介绍
2016/10/27 Javascript
完美解决IE不支持Data.parse()的问题
2016/11/24 Javascript
AngularJS实现网站换肤实例
2021/02/19 Javascript
JavaScript 中 apply 、call 的详解
2017/03/21 Javascript
原生JS实现导航下拉菜单效果
2020/11/25 Javascript
详解如何创建并发布一个 vue 组件
2018/11/08 Javascript
jQuery+ThinkPHP实现图片上传
2020/07/23 jQuery
Python文件读取的3种方法及路径转义
2015/06/21 Python
Python 关于反射和类的特殊成员方法
2017/09/14 Python
python3.5 email实现发送邮件功能
2018/05/22 Python
Python列表解析配合if else的方法
2018/06/23 Python
python3实现随机数
2018/06/25 Python
python 列表,数组和矩阵sum的用法及区别介绍
2018/06/28 Python
Python3实现从排序数组中删除重复项算法分析
2019/04/03 Python
深入浅析Python 中 is 语法带来的误解
2019/05/07 Python
Python多进程方式抓取基金网站内容的方法分析
2019/06/03 Python
一行Python代码过滤标点符号等特殊字符
2019/08/12 Python
美国设计师精美珠宝购物网:Netaya
2016/08/28 全球购物
Lookfantastic阿联酋官网:英国知名美妆护肤购物网站
2020/05/26 全球购物
写一个函数,要求输入一个字符串和一个字符长度,对该字符串进行分隔
2015/07/30 面试题
技校生自我鉴定
2013/12/08 职场文书
中学生爱国演讲稿
2013/12/31 职场文书
自荐信的基本格式
2014/02/22 职场文书
党风廉洁教育心得体会
2016/01/20 职场文书
2016大学生求职自荐信范文
2016/01/28 职场文书
提取视频中的音频 Python只需要三行代码!
2021/05/10 Python