aiml语言python对话系统构建

来源:互联网 发布:js数组地址指向 编辑:程序博客网 时间:2024/06/05 22:09

AIML是一种为了匹配模式和确定响应而进行规则定义的 XML 格式。

安装aiml for python2:

pip install aiml

为了便于讲解,首先贴出aiml语言python代码如下:

#! /usr/bin/env python2.7#coding=utf-8import syssys.path.insert(0, "../")import aiml# The Kernel object is the public interface to# the AIML interpreter.k = aiml.Kernel()# Use the 'learn' method to load the contents# of an AIML file into the Kernel.k.learn("cn-startup.xml")k.respond("load aiml cn")while True:    query=raw_input("> ")    response = k.respond(query)    print response
在文件cn-startup.xml中定义了需要学习的模式匹配文件,如下:

<aiml version="1.0"><category><pattern>LOAD AIML CN</pattern><template><!-- Load chinese AIML set --><!-- <learn>cn-profile.aiml</learn> --><learn>cn-test1.aiml</learn>
<learn>cn-test2.aiml</learn>
</template></category></aiml>

cn-test1.aiml,cn-test2.aiml即为我们自己定义的模式匹配文件,例如我们在cn-test1.aiml中要定义问候的回答,则可以边界cn-test1.aiml如下:

<?xml version="1.0" encoding="UTF-8"?><aiml version="1.0"><!--问候--> <category>    <pattern>你好</pattern>    <template>        <srai>HELLO</srai>    </template></category> <category>    <pattern>hi</pattern>    <template>        hi!    </template></category><category>    <pattern>HELLO</pattern>    <template>        <random>            <li>你好.</li>            <li>你也好.</li>            <li>你好啊.</li>        </random>    </template></category></aiml>
文件中pattern为用于匹配选项,如果用于输入刚好与pattern匹配(匹配方式为正则匹配),则输出对应的template中的内容.例如用于输入:hi,则输出回答为:hi!
对于构建对话系统,我们需要设计对话的pattern,template,得到.aiml文件之后在cn-startup.xml添加该.aiml文件,那么就可以通过k.learn函数学习该文件.