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使用rsa加密算法模块模拟新浪微博登录
Jan 22 Python
python如何实现int函数的方法示例
Feb 19 Python
python用户管理系统
Mar 13 Python
Python实现购物车购物小程序
Apr 18 Python
wxPython的安装与使用教程
Aug 31 Python
Python实现计算字符串中出现次数最多的字符示例
Jan 21 Python
python实现XML解析的方法解析
Nov 16 Python
python GUI库图形界面开发之PyQt5图片显示控件QPixmap详细使用方法与实例
Feb 27 Python
Python的in,is和id函数代码实例
Apr 18 Python
如何使用python切换hosts文件
Apr 29 Python
Appium+Python实现简单的自动化登录测试的实现
Jan 26 Python
我对PyTorch dataloader里的shuffle=True的理解
May 20 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
smarty中先strip_tags过滤html标签后truncate截取文章运用
2010/10/25 PHP
Discuz7.2版的faq.php SQL注入漏洞分析
2014/08/06 PHP
PHP+MySQL删除操作实例
2015/01/21 PHP
CI框架集成Smarty的方法分析
2016/05/17 PHP
javascript HTMLEncode HTMLDecode的完整实例(兼容ie和火狐)
2009/06/02 Javascript
javascript来定义类的规范小结
2010/11/19 Javascript
jquery固定底网站底部菜单效果
2013/08/13 Javascript
js同比例缩放图片的小例子
2013/10/30 Javascript
jQuery控制Div拖拽效果完整实例分析
2015/04/15 Javascript
Vue.js每天必学之计算属性computed与$watch
2016/09/05 Javascript
js利用clipboardData实现截屏粘贴功能
2016/10/12 Javascript
ES6新特性之Symbol类型用法分析
2017/03/31 Javascript
bootstrap table插件的分页与checkbox使用详解
2017/07/23 Javascript
vue移动端路由切换实例分析
2018/05/14 Javascript
解决微信小程序防止无法回到主页的问题
2018/09/28 Javascript
Nodejs + sequelize 实现增删改查操作
2020/11/07 NodeJs
JavaScript实现简单动态表格
2020/12/02 Javascript
微信小程序组件生命周期的踩坑记录
2021/03/03 Javascript
利用python 更新ssh 远程代码 操作远程服务器的实现代码
2018/02/08 Python
pycharm远程开发项目的实现步骤
2019/01/20 Python
python+numpy按行求一个二维数组的最大值方法
2019/07/09 Python
在python Numpy中求向量和矩阵的范数实例
2019/08/26 Python
使用pyplot.matshow()函数添加绘图标题
2020/06/16 Python
python怎么判断模块安装完成
2020/06/19 Python
《与朱元思书》的教学反思
2014/04/17 职场文书
金融事务专业求职信
2014/04/25 职场文书
说明书格式及范文
2014/05/07 职场文书
永远跟党走演讲稿
2014/09/12 职场文书
党员十八大心得体会
2014/09/12 职场文书
学生实习证明模板汇总
2014/09/25 职场文书
群众路线教育实践活动个人对照检查材料思想汇报(社区班子)
2014/10/06 职场文书
2014年团工作总结
2014/11/27 职场文书
初中中等生评语
2014/12/29 职场文书
小学生必读成语故事大全:送给暑假的你们
2019/07/09 职场文书
mongodb清除连接和日志的正确方法分享
2021/09/15 MongoDB
AudioContext 实现音频可视化(web技术分享)
2022/02/24 Javascript