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

这篇文章主要为大家详细介绍了AI人工智能应用,本文拟使用Python开发语言实现类似于WIndows平台的“小娜”,,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

本文拟使用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库

?
1
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了:

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

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

4、 与alice聊天

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

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

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

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

这里写两个方法:

  get:渲染界面

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

  Class类的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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. 接口调用  

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$.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服务端代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python
 
# -*- coding: utf-8 -*-
 
import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
 
import os
import aiml
 
os.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前端代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<!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 >

【系统测试】

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

2、调用测试

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

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

【可能遇到问题】  

中文乱码

【系统展望】

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

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

原文链接:https://www.cnblogs.com/qixiaoyizhan/p/7246387.html

### 回答1: 图灵测试是一种用来测试人工智能是否具有人类般智能的方法。这项测试由英国数学家阿兰·图灵提出,并在他的论文《计算机和智慧》中进行了解释。 图灵测试的基本思想是,如果一个人无法从另一个人的言辞或行为中分辨出这个人是人还是机器,那么这个机器就具有了人类般的智能。因此,图灵测试通常被认为是人工智能与人类智能的界限。 下面是一个用 Python 实现图灵测试的例子: ``` def turing_test(ai): human_score = 0 machine_score = 0 # 问人类一些问题 human_answers = ask_questions_to_human() for answer in human_answers: if answer is not None: human_score += 1 # 问 AI 一些问题 machine_answers = ai.ask_questions() for answer in machine_answers: if answer is not None: machine_score += 1 # 如果 AI 的得分超过人类,则认为 AI 具有人类般的智能 if machine_score > human_score: return True else: return False ``` 在上面的代码中,我们首先向人类询问一些问题,然后记录人类回答问题的数量。然后,我们调用 AI 的 `ask_questions` 方法,向 AI 询问一些问题,并记录 AI 回答问题的数量。最后,我们比较人类和 AI 回答问 ### 回答2: Python是一种功能强大且易于学习的编程语言,可用于编写图灵测试程序。图灵测试是一种人工智能的测试方法,通过与人类进行对话,测试机器是否能够表现出与人类相似的智能。 在Python中,可以使用第三方实现与图灵测试相关的功能,例如使用requests来发送HTTP请求,获取图灵机器人API的响应。首先,需要在图灵机器人的官网注册账号并获取API密钥。 接下来,可以使用以下代码片段来实现与图灵机器人的对话: ```python import requests api_key = "your_api_key" base_url = "http://openapi.tuling123.com/openapi/api/v2" # 图灵机器人API的基础URL def get_turing_response(message): headers = {'Content-Type': 'application/json;charset=UTF-8'} payload = { "perception": { "inputText": { "text": message } }, "userInfo": { "apiKey": api_key, "userId": "1" } } response = requests.post(base_url, json=payload, headers=headers) response_json = response.json() return response_json["results"][0]["values"]["text"] # 使用示例 while True: user_input = input("你:") response = get_turing_response(user_input) print("机器人:" + response) ``` 上述代码中,首先通过API密钥和用户输入构建一个包含用户信息和输入文本的JSON对象。然后,使用requests向图灵机器人的API发送POST请求,并将返回的JSON响应解析,提取机器人的回答并输出到控制台。 这样,我们就可以使用Python编写一个简单的图灵测试程序,与机器人进行对话,并观察机器人是否能够表现出与人类相似的智能。 ### 回答3: 图灵测试是利用人工智能技术来模拟人类智能的一种方法,Python作为一种高级编程语言,具有简洁、易读易写的特点,非常适合用来编写图灵测试。 编写图灵测试的关键在于实现一个聊天机器人,使其能够对话并模拟人类的回答。首先,我们需要定义机器人的问题,这些问题可以是与特定主题或随机话题相关的。然后,我们需要给每个问题定义相应的答案,这些答案可以事先准备好,也可以通过爬取互联网或使用自然语言处理技术来生成。 接下来,我们可以使用Python的自然语言处理,如NLTK或SpaCy,来进行文本预处理和分词。这些可以将输入的自然语言句子进行分解和处理,以便于后续的回答匹配和语义理解。 在编写图灵测试程序时,可以使用Python的条件语句和循环结构来处理用户输入。根据用户的问题,我们可以遍历问题中的问题,通过语义相似度匹配或关键词匹配来寻找相应的答案。对于匹配的问题,我们可以将其相应的答案返回给用户。如果没有匹配到合适的问题,我们可以选择给出一个默认回答或者提示用户重新输入。 除了基本的问答功能,我们还可以通过给机器人添加一些逻辑判断和对话流程,使其具备更复杂的智能行为。例如,我们可以使用Python的模块化编程来实现对话流程的管理,通过定义不同的模块和函数来处理特定的问题或场景。 总的来说,使用Python编写图灵测试程序较为简单,只需利用Python的文本处理和逻辑判断的特性即可实现一个基本的回答机器人。当然,如果要实现更复杂的图灵测试程序,可能需要结合其他的人工智能技术和大数据处理方法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值