国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

AI人工智能 Python實現(xiàn)人機對話

2020-01-04 16:32:22
字體:
供稿:網(wǎng)友

在人工智能進展的如火如荼的今天,我們?nèi)绻粐L試去接觸新鮮事物,馬上就要被世界淘汰啦~

本文擬使用Python開發(fā)語言實現(xiàn)類似于WIndows平臺的“小娜”,或者是IOS下的“Siri”。最終達到人機對話的效果。

【實現(xiàn)功能】

這篇文章將要介紹的主要內(nèi)容如下:

  1、搭建人工智能--人機對話服務(wù)端平臺
  2、實現(xiàn)調(diào)用服務(wù)端平臺進行人機對話交互

【實現(xiàn)思路】

  AIML

  AIML由Richard Wallace發(fā)明。他設(shè)計了一個名為 A.L.I.C.E. (Artificial Linguistics Internet Computer Entity 人工語言網(wǎng)計算機實體) 的機器人,并獲得了多項人工智能大獎。有趣的是,圖靈測試的其中一項就在尋找這樣的人工智能:人與機器人通過文本界面展開數(shù)分鐘的交流,以此查看機器人是否會被當(dāng)作人類。

  本文就使用了Python語言調(diào)用AIML庫進行智能機器人的開發(fā)。

  本系統(tǒng)的運作方式是使用Python搭建服務(wù)端后臺接口,供各平臺可以直接調(diào)用。然后客戶端進行對智能對話api接口的調(diào)用,服務(wù)端分析參數(shù)數(shù)據(jù),進行語句的分析,最終返回應(yīng)答結(jié)果。

  當(dāng)前系統(tǒng)前端使用HTML進行簡單地聊天室的設(shè)計與編寫,使用異步請求的方式渲染數(shù)據(jù)。

【開發(fā)及部署環(huán)境】

開發(fā)環(huán)境:Windows 7 ×64 英文版

     JetBrains PyCharm 2017.1.3 x64

測試環(huán)境:Windows 7 ×64 英文版

【所需技術(shù)】

  1、Python語言的熟練掌握,Python版本2.7
  2、Python服務(wù)端開發(fā)框架tornado的使用
  3、aiml庫接口的簡單使用
  4、HTML+CSS+Javascript(jquery)的熟練使用
  5、Ajax技術(shù)的掌握

【實現(xiàn)過程】

1、安裝Python aiml庫

pip install aiml

2、獲取alice資源

Python aiml安裝完成后在Python安裝目錄下的 Lib/site-packages/aiml下會有alice子目錄,將此目錄復(fù)制到工作區(qū)。
或者在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') # 將工作區(qū)目錄切換到剛才復(fù)制的alice文件夾alice = aiml.Kernel()alice.learn("startup.xml")alice.respond('LOAD ALICE')

注意加載時需要切換工作目錄到alice(剛才復(fù)制的文件夾)下。

4、 與alice聊天

加載之后就可以與alice聊天了,每次只需要調(diào)用respond接口:

alice.respond('hello') #這里的hello即為發(fā)給機器人的信息 

5. 用Tornado搭建聊天機器人網(wǎng)站  

Tornado可以很方便地搭建一個web網(wǎng)站的服務(wù)端,并且接口風(fēng)格是Rest風(fēng)格,可以很方便搭建一個通用的服務(wù)端接口。

這里寫兩個方法:

  get:渲染界面

  post:獲取請求參數(shù),并分析,返回聊天結(jié)果

  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. 簡單搭建一個聊天界面  

AI,人工智能,Python,人機對話

該界面是基于BootStrap的,我們簡單搭建這么一個聊天的界面用于展示我們的接口結(jié)果。同時進行簡單的聊天。

7. 接口調(diào)用  

我們異步請求服務(wù)端接口,并將結(jié)果渲染到界面 

 $.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

這里我附上系統(tǒng)的完整目錄結(jié)構(gòu)以及完整代碼->

8、目錄結(jié)構(gòu)

AI,人工智能,Python,人機對話

9、Python服務(wù)端代碼

#!/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="qixiao.ico" type="image/x-icon"/>  <title>qixiao tools</title> <link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css"> <script type="text/javascript" src="../static/js/jquery-3.2.0.min.js"></script> <script type="text/javascript" src="../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="/" 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="/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>

【系統(tǒng)測試】

1、首先我們將我們的服務(wù)運行起來

AI,人工智能,Python,人機對話

2、調(diào)用測試

然后我們進行前臺界面的調(diào)用

AI,人工智能,Python,人機對話

AI,人工智能,Python,人機對話

這里我們可以看到,我們的項目完美運行,并且達到預(yù)期效果。

【可能遇到問題】  

中文亂碼

【系統(tǒng)展望】

經(jīng)過測試,中文目前不能進行對話,只能使用英文進行對話操作,有待改善。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 布尔津县| 吉水县| 泰安市| 莎车县| 平阳县| 贵溪市| 合水县| 霍山县| 西林县| 南华县| 宽甸| 鄂尔多斯市| 新和县| 庐江县| 文成县| 定日县| 六枝特区| 剑阁县| 邮箱| 横峰县| 乳源| 财经| 卓资县| 华池县| 雷山县| 元朗区| 康保县| 阜新市| 临江市| 和顺县| 芮城县| 安远县| 讷河市| 布尔津县| 叙永县| 黄骅市| 隆德县| 沙雅县| 镇康县| 长寿区| 开江县|