一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python实现聊天机器人的示例代码

时间:2018-07-10 编辑:猪哥 来源:一聚教程网

一、AIML是什么

AIML全名为Artificial Intelligence Markup Language(人工智能标记语言),是一种创建自然语言软件代理的XML语言,是由RichardS. Wallace 博士和Alicebot开源软件组织于1995-2000年间发明创造的。AIML是一种为了匹配模式和确定响应而进行规则定义的 XML 格式。

二、实现第一个聊天机器人

(一)安装Python aiml库

pip install aiml

(二)获取alice资源

Python aiml安装完成后在Python安装目录下的 site-packages的aiml下会有alice子目录(比如D:Program FilesPython36Libsite-packagesaimlbotdataalice),这个是系统自带的一个简单的英文语料库。

(三)编程实现机器人聊天

1 程序

# -*- coding: utf-8 -*-
import aiml
import sys
import os
 
 
def get_module_dir(name):
 print("module", sys.modules[name])
 path = getattr(sys.modules[name], '__file__', None)
 print(path)
 if not path:
  raise AttributeError('module %s has not attribute __file__' % name)
 return os.path.dirname(os.path.abspath(path))
 
 
alice_path = get_module_dir('aiml') + '\botdata\alice'

os.chdir(alice_path)  # 切换到语料库所在工作目录

alice = aiml.Kernel()  # 创建机器人alice对象
alice.learn("startup.xml") # 加载...\botdata\alice\startup.xml
alice.respond('LOAD ALICE') # 加载...\botdata\alice目录下的语料库
 
while True:
 message = input("Enter your message >> ")
 if("exit" == message):
  exit()
 response = alice.respond(message) # 机器人应答
 print(response)

2 运行结果

热门栏目