侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

AI人工智能 Python实现人机对话

Python  /  管理员 发布于 7年前   158

在人工智能进展的如火如荼的今天,我们如果不尝试去接触新鲜事物,马上就要被世界淘汰啦~

本文拟使用Python开发语言实现类似于WIndows平台的“小娜”,或者是IOS下的“Siri”。最终达到人机对话的效果。

【实现功能】

这篇文章将要介绍的主要内容如下:

  1、搭建人工智能--人机对话服务端平台
  2、实现调用服务端平台进行人机对话交互

【实现思路】

  AIML

  AIML由Richard Wallace发明。他设计了一个名为 A.L.I.C.E. (Artificial Linguistics Internet Computer Entity 人工语言网计算机实体) 的机器人,并获得了多项人工智能大奖。有趣的是,图灵测试的其中一项就在寻找这样的人工智能:人与机器人通过文本界面展开数分钟的交流,以此查看机器人是否会被当作人类。

  本文就使用了Python语言调用AIML库进行智能机器人的开发。

  本系统的运作方式是使用Python搭建服务端后台接口,供各平台可以直接调用。然后客户端进行对智能对话api接口的调用,服务端分析参数数据,进行语句的分析,最终返回应答结果。

  当前系统前端使用HTML进行简单地聊天室的设计与编写,使用异步请求的方式渲染数据。

【开发及部署环境】

开发环境:Windows 7 ×64 英文版

     JetBrains PyCharm 2017.1.3 x64

测试环境:Windows 7 ×64 英文版

【所需技术】

  1、Python语言的熟练掌握,Python版本2.7
  2、Python服务端开发框架tornado的使用
  3、aiml库接口的简单使用
  4、HTML+CSS+Javascript(jquery)的熟练使用
  5、Ajax技术的掌握

【实现过程】

1、安装Python aiml库

pip install aiml

2、获取alice资源

Python aiml安装完成后在Python安装目录下的 Lib/site-packages/aiml下会有alice子目录,将此目录复制到工作区。
或者在Google code上下载alice brain: aiml-en-us-foundation-alice.v1-9.zip

3、Python下加载alice

取得alice资源之后就可以直接利用Python aiml库加载alice brain了:

import aimlos.chdir('./src/alice') # 将工作区目录切换到刚才复制的alice文件夹alice = aiml.Kernel()alice.learn("startup.xml")alice.respond('LOAD ALICE')

注意加载时需要切换工作目录到alice(刚才复制的文件夹)下。

4、 与alice聊天

加载之后就可以与alice聊天了,每次只需要调用respond接口:

alice.respond('hello') #这里的hello即为发给机器人的信息 

5. 用Tornado搭建聊天机器人网站  

Tornado可以很方便地搭建一个web网站的服务端,并且接口风格是Rest风格,可以很方便搭建一个通用的服务端接口。

这里写两个方法:

  get:渲染界面

  post:获取请求参数,并分析,返回聊天结果

  Class类的代码如下:

class ChatHandler(tornado.web.RequestHandler): def get(self): self.render('chat.html') def post(self): try:  message = self.get_argument('msg', None)  print(str(message))  result = {  'is_success': True,  'message': str(alice.respond(message))  }  print(str(result))  respon_json = tornado.escape.json_encode(result)  self.write(respon_json) except Exception, ex:  repr(ex)  print(str(ex))  result = {  'is_success': False,  'message': ''  }  self.write(str(result))

6. 简单搭建一个聊天界面  

该界面是基于BootStrap的,我们简单搭建这么一个聊天的界面用于展示我们的接口结果。同时进行简单的聊天。

7. 接口调用  

我们异步请求服务端接口,并将结果渲染到界面 

 $.ajax({ type: 'post',  url: AppDomain+'chat',  async: true,//异步  dataType: 'json',  data: (  {  "msg":request_txt  }),  success: function (data)  {   console.log(JSON.stringify(data));   if (data.is_success == true) {   setView(resUser,data.message);  }  },  error: function (data)  {  console.log(JSON.stringify(data)); } });//end Ajax

这里我附上系统的完整目录结构以及完整代码->

8、目录结构

9、Python服务端代码

#!/usr/bin/env python# -*- coding: utf-8 -*-import os.pathimport tornado.authimport tornado.escapeimport tornado.httpserverimport tornado.ioloopimport tornado.optionsimport tornado.webfrom tornado.options import define, optionsimport osimport aimlos.chdir('./src/alice')alice = aiml.Kernel()alice.learn("startup.xml")alice.respond('LOAD ALICE')define('port', default=3999, help='run on the given port', type=int)class Application(tornado.web.Application): def __init__(self): handlers = [  (r'/', MainHandler),  (r'/chat', ChatHandler), ] settings = dict(  template_path=os.path.join(os.path.dirname(__file__), 'templates'),  static_path=os.path.join(os.path.dirname(__file__), 'static'),  debug=True, ) # conn = pymongo.Connection('localhost', 12345) # self.db = conn['demo'] tornado.web.Application.__init__(self, handlers, **settings)class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') def post(self): result = {  'is_success': True,  'message': '123' } respon_json = tornado.escape.json_encode(result) self.write(str(respon_json)) def put(self): respon_json = tornado.escape.json_encode("{'name':'qixiao','age':123}") self.write(respon_json)class ChatHandler(tornado.web.RequestHandler): def get(self): self.render('chat.html') def post(self): try:  message = self.get_argument('msg', None)  print(str(message))  result = {  'is_success': True,  'message': str(alice.respond(message))  }  print(str(result))  respon_json = tornado.escape.json_encode(result)  self.write(respon_json) except Exception, ex:  repr(ex)  print(str(ex))  result = {  'is_success': False,  'message': ''  }  self.write(str(result))def main(): tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()if __name__ == '__main__': print('HTTP server starting ...') main()

9、Html前端代码

 <!DOCTYPE html><html><head> <link rel="icon" href="https:/article/qixiao.ico" type="image/x-icon"/>  <title>qixiao tools</title> <link rel="stylesheet" type="text/css" href="https:/article/../static/css/bootstrap.min.css"> <script type="text/javascript" src="https:/article/../static/js/jquery-3.2.0.min.js"></script> <script type="text/javascript" src="https:/article/../static/js/bootstrap.min.js"></script> <style type="text/css"> .top-margin-20{  margin-top: 20px; } #result_table,#result_table thead th{  text-align: center; } #result_table .td-width-40{  width: 40%; } </style> <script type="text/javascript"> </script> <script type="text/javascript"> var AppDomain = 'http://localhost:3999/' $(document).ready(function(){  $("#btn_sub").click(function(){  var user = 'qixiao(10011)';  var resUser = 'alice (3333)';  var request_txt = $("#txt_sub").val();  setView(user,request_txt);  $.ajax({   type: 'post',   url: AppDomain+'chat',   async: true,//异步   dataType: 'json',   data: (   {   "msg":request_txt   }),   success: function (data)   {   console.log(JSON.stringify(data));   if (data.is_success == true) {    setView(resUser,data.message);   }   },   error: function (data)   {   console.log(JSON.stringify(data));   }  });//end Ajax    }); }); function setView(user,text) {  var subTxt = user + " "+new Date().toLocaleTimeString() +'\n・'+ text;  $("#txt_view").val($("#txt_view").val()+'\n\n'+subTxt);  var scrollTop = $("#txt_view")[0].scrollHeight;   $("#txt_view").scrollTop(scrollTop);  } </script></head><body class="container"> <header class="row"> <header class="row">  <a href="https:" class="col-md-2" style="font-family: SimHei;font-size: 20px;text-align:center;margin-top: 30px;">  <span class="glyphicon glyphicon-home"></span>Home  </a>  <font class="col-md-4 col-md-offset-2" style="font-family: SimHei;font-size: 30px;text-align:center;margin-top: 30px;">  <a href="https:tools" style="cursor: pointer;">QiXiao - Chat</a>  </font> </header> <hr> <article class="row">  <section class="col-md-10 col-md-offset-1" style="border:border:solid #4B5288 1px;padding:0">Admin : QiXiao </section>  <section class="col-md-10 col-md-offset-1 row" style="border:solid #4B5288 1px;padding:0">  <section class="col-md-9" style="height: 400px;">   <section class="row" style="height: 270px;">   <textarea class="form-control" style="width:100%;height: 100%;resize: none;overflow-x: none;overflow-y: scroll;" readonly="true" id="txt_view"></textarea>   </section>   <section class="row" style="height: 130px;border-top:solid #4B5288 1px; ">   <textarea class="form-control" style="overflow-y: scroll;overflow-x: none;resize: none;width: 100%;height:70%;border: #fff" id="txt_sub"></textarea>   <button class="btn btn-primary" style="float: right;margin: 0 5px 0 0" id="btn_sub">Submit</button>   </section>  </section>  <section class="col-md-3" style="height: 400px;border-left: solid #4B5288 1px;"></section>  </section> </article> </body> </html>

【系统测试】

1、首先我们将我们的服务运行起来

2、调用测试

然后我们进行前台界面的调用

这里我们可以看到,我们的项目完美运行,并且达到预期效果。

【可能遇到问题】

中文乱码

【系统展望】

经过测试,中文目前不能进行对话,只能使用英文进行对话操作,有待改善。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python中import机制详解
    下一条:
    Python编程实现蚁群算法详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客