Python学习分享

超赞!快来用Python的搭建你的AI老婆吧!

2019-06-11  本文已影响3人  烟雨丿丶蓝

夏天太热,又不想出门,就让我们用的Python来搭建属于自己的〜可以对话的AI老婆吧〜

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

image

【实现功能】

柳猫将会从下面两个方面开始:

1.搭建人工智能 - 人机对话服务端平台

2.实现调用服务端平台进行人机对话交互

【实现思路】

AIML

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

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

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

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

在这推荐下小编创建的Python学习交流群835017344,可以获取Python入门基础教程,送给每一位小伙伴,这里是小白聚集地,每天还会直播和大家交流分享经验哦,欢迎初学和进阶中的小伙伴。


【开发及部署环境】

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

JetBrains PyCharm 2017.1.3 x64

测试环境:Windows 7×64

【所需技术】

小伙伴们,如果要完全理解,请熟练以下技能(不会也​​没关系啦,一起学习就好了):

  1. Python的语言的熟练掌握,Python的版本2.7及以上
  2. Python的服务端开发框架龙卷风的使用
  3. AIML库接口的简单使用
  4. HTML + CSS +的JavaScript(jQuery的)的熟练使用
  5. Ajax的技术的掌握
image

【实现过程】

1.安装Python aiml库

<pre class="hljs nginx" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">pip install aiml</pre>

2.获取alice资源

Python aiml安装完成后在Python安装目录下的Lib / site-packages / aiml下会有alice子目录,将此目录复制到工作区。

或者在谷歌代码上下载

<pre class="hljs css" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">alice brain:aiml-en-us-foundation-alice.v1-9.zip</pre>

3. Python下加载alice

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

<pre class="prettyprint hljs lua" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">进口目的
os.chdir('./ src / alice')#将工作区目录切换到刚才复制的alice文件夹
alice = aiml.Kernel()
alice.learn( “startup.xml”)
alice.respond('LOAD ALICE')</pre>

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

4.与alice聊天

加载之后就可以与爱丽丝聊天了,每次只需要调用响应接口:

<pre class="hljs lua" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">alice.respond('hello')#这里的hello即为发给机器人的信息</pre>

柳猫紧接上篇,现在我们来实现AI老婆的对话(画脸):

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

龙卷风可以很方便地搭建一个网络网站的服务端,并且接口风格是休闲风格,可以很方便搭建一个通用的服务端接口。

这里写两个方法:

<pre class="hljs" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">得到:渲染界面
岗位:获取请求参数,并分析,返回聊天结果</pre>

类类的代码如下:

<pre class="prettyprint hljs ruby" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">class ChatHandler(tornado.web.RequestHandler):
def get(self):
self.render( 'chat.html')
def post(self):
尝试:
message = self.get_argument('msg',None)
打印(STR(消息))
result = {
'is_success':是的,
'message':str(alice.respond(message))
}
打印(STR(结果))
respon_json = tornado.escape.json_encode(结果)
self.write(respon_json)
除了例外,例如:
再版(前)
打印(STR(前))
result = {
'is_success':错,
'信息': ''
}
self.write(STR(结果))</pre>

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

image

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

7.接口调用

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

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">$就({
类型:'post',
url:AppDomain +'chat',
async:true,//异步
dataType:'json',
数据:(
{
“味精”:request_txt
}),
成功:功能(数据)
{
的console.log(JSON.stringify(数据));
if(data.is_success == true){
的setView(resUser,data.message);
}
},
错误:功能(数据)
{
的console.log(JSON.stringify(数据));
}
}); //结束Ajax</pre>

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

8.目录结构

image

9. Python服务端代码

<pre class="prettyprint hljs ruby" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">#!/ usr / bin / env python
# - * - 编码:utf-8 - * -
import os.path
导入tornado.auth
导入tornado.escape
import tornado.httpserver
import tornado.ioloop
导入tornado.options
import tornado.web
来自tornado.options导入定义,选项
进口口
进口目的
os.chdir( './ SRC /爱丽丝')
alice = aiml.Kernel()
alice.learn( “startup.xml”)
alice.respond('LOAD ALICE')
define('port',default = 3999,help ='在给定端口上运行',type = int)
class Application(tornado.web.Application):
def init (self):
处理程序= [
(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'),
调试=真,

#conn = pymongo.Connection('localhost',12345)
#self.db = conn ['demo']
tornado.web.Application .
init (自我,处理程序,**设置)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render( '的index.html')
def post(self):
result = {
'is_success':是的,
'message':'123'
}
respon_json = tornado.escape.json_encode(结果)
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):
尝试:
message = self.get_argument('msg',None)
打印(STR(消息))
result = {
'is_success':是的,
'message':str(alice.respond(message))
}
打印(STR(结果))
respon_json = tornado.escape.json_encode(结果)
self.write(respon_json)
除了例外,例如:
再版(前)
打印(STR(前))
result = {
'is_success':错,
'信息': ''
}
self.write(STR(结果))
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance()。开始()
如果name =='
main
':
print('HTTP服务器启动...')
主要()</pre>

10. Html前端代码

<pre class="prettyprint hljs xml" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><!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利润率-20 {
margin-top:20px;
}
#result_table,#result_table thead th {
text-align:center;
}
#result_table .td-width-40 {
宽度:40%;
}
</样式>
<script type =“text / javascript”> </ SCRIPT>
<script type =“text / javascript”> var AppDomain ='http:// localhost:3999 /'
(文件)。就绪(函数(){( “#btn_sub”)。点击(函数(){
var user ='qixiao(10011)';
var resUser ='alice(3333)';
var request_txt = (“#txt_sub”)。val(); 的setView(用户,request_txt);就({
类型:'post',
url:AppDomain +'chat',
async:true,//异步
dataType:'json',
数据:(
{
“味精”:request_txt
}),
成功:功能(数据)
{
的console.log(JSON.stringify(数据));
if(data.is_success == true){
的setView(resUser,data.message);
}
},
错误:功能(数据)
{
的console.log(JSON.stringify(数据));
}
}); //结束Ajax

        });
    });
    函数setView(用户,文本)
    {
        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>主页
</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;">奇晓 - 聊天</a>
</ FONT>
</报头>
<HR>
<article class =“row”>
<section class =“col-md-10 col-md-offset-1”style =“border:border:solid#4B5288 1px; padding:0”>管理员: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 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”>提交</ button>
</节>
</节>
<section class =“col-md-3”style =“height:400px; border-left:solid#4B5288 1px;”> </ section>
</节>
</文章>
</ BODY>
</ HTML></pre>

【系统测试】

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

image

2.调用测试

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

image image

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

上一篇 下一篇

猜你喜欢

热点阅读