Python如何实现机器人聊天
今天午休的时候,无意之中看了一篇博客,名字叫Python实现机器人,感觉挺有的意思的。
于是用其写了一个简单的Python聊天,源码如下所示:
#-*-coding:utf-8-*-
importaiml
importsys
importos
defget_module_dir(name):
print("module",sys.modules[name])
path=getattr(sys.modules[name],'__file__',None)
print(path)
ifnotpath:
raiseAttributeError('module%shasnotattribute__file__'%name)
returnos.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('LOADALICE')#加载...\\botdata\\alice目录下的语料库
whileTrue:
message=input("Enteryourmessage>>")
if("exit"==message):
exit()
response=alice.respond(message)#机器人应答
print(response)
注意:如果出现某某模块找不到的时候,记得使用pip安装对应的模块。
效果图如下所示:
唯一美中不足的是英文,不过没关系,国内有图灵机器人。
代码如下所示:
fromurllib.requestimporturlopen,Request
fromurllib.errorimportURLError
fromurllib.parseimporturlencode
importjson
classTuringChatMode(object):
"""thismodebaseonturingrobot"""
def__init__(self):
#API接口地址
self.turing_url='http://www.tuling123.com/openapi/api?'
defget_turing_text(self,text):
'''请求方式:HTTPPOST
请求参数:参数是否必须长度说明
key必须32APIkey
info必须1-32请求内容,编码方式为"utf-8"
userid必须32MAC地址或ID
'''
turing_url_data=dict(
key='fcbf9efe277e493993e889eabca5b331',
info=text,
userid='60-14-B3-BA-E1-4D',
)
#print("ThethingstoRequestis:",self.turing_url+urlencode(turing_url_data))
self.request=Request(self.turing_url+urlencode(turing_url_data))
#print("TheresultofRequestis:",self.request)
try:
w_data=urlopen(self.request)
#print("Typeofthedatafromurlopen:",type(w_data))
#print("Thedatafromurlopenis:",w_data)
exceptURLError:
raiseIndexError("Nointernetconnectionavailabletotransfertxtdata")
#如果发生网络错误,断言提示没有可用的网络连接来传输文本信息
except:
raiseKeyError("Serverwouldn'trespond(invalidkeyorquotahasbeenmaxedout)")
#其他情况断言提示服务相应次数已经达到上限
response_text=w_data.read().decode('utf-8')
#print("Typeoftheresponse_text:",type(response_text))
#print("response_text:",response_text)
json_result=json.loads(response_text)
#print("Typeofthejson_result:",type(json_result))
returnjson_result['text']
if__name__=='__main__':
print("Nowucantypeinsomething&inputqtoquit")
turing=TuringChatMode()
whileTrue:
msg=input("\nMaster:")
ifmsg=='q':
exit("urquitthechat!")#设定输入q,退出聊天。
else:
turing_data=turing.get_turing_text(msg)
print("Robot:",turing_data)
效果图如下:
可能由于机器人智能太低了,有点答非所问。
更多精彩可以去图灵机器人官网了解:http://www.tuling123.com
编程的世界是有趣的,你去探索,你会发现很多有意思的事情。
以上就是Python如何实现机器人聊天的详细内容,更多关于python实现机器人聊天的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。