图灵接口及电脑语音聊天
一,图灵接口
- 注册账号创建机器人 (http://www.tuling123.com/member/robot/index.jhtml)
- api接口文档 (https://www.kancloud.cn/turing/www-tuling123-com/718227)
- 数据接口地址 (http://openapi.tuling123.com/openapi/api/v2)
- 请求方式:http post,请求参数为json
- urlopen,Request (urlopen:打开一个连接,Request:是用来封装打开一个链接的时候你可能需要提交一些数据)
-
from urllib.request import urlopen,Request
-
单纯的访问用urlopen就可以
-
但是需要post提交数据就得用request结合提交数据体
- 代码编写 图灵接口.py:
from urllib.request import urlopen,Request #urlopen:打开一个连接,Request:是用来封装打开一个链接的时候你可能需要提交一些数据) import json def tl_func(qusetion): url = 'http://openapi.tuling123.com/openapi/api/v2' data = json.dumps({ "perception": { "inputText": { "text": "%s" % qusetion }, }, "userInfo": { "apiKey": "08a4694a51b145b4ab7178d86a1ae8d7", "userId": "D46D6DD8273C" #D4-6D-6D-D8-27-3C } }).encode('utf-8') headers = {'Content-Type':'application/json'} req = Request(url=url,data=data) response = json.loads(urlopen(req).read().decode('utf-8')) #josn.loads 定义返回数据类型为字典 #print(response['results'][0]['values']['text']) #取出图灵返回的数据值 result = response['results'] res = '' for var in result: res += '/n'.join(list((var['values'].values()))) #这个意思是不管图灵返回几个数据 我们都依次取出来以换行的形式拼接起来,变成一行一行的数据 else: return res return None def main(): result = tl_func(qusetion) print(result) if __name__ == '__main__': qusetion = '你叫什么呀' main() ''' 下面是取出response返回的字典数据结构,然后可以取出图灵返回的数据,提供参考 { 'intent': {'actionName': '', 'code': 10004, 'intentName': ''}, 'results': [ { 'resultType': 'text', 'values': {'text': '我们每天都打招呼吧'}, 'groupType': 1 } ], 'emotion': { 'robotEmotion': {'d': 0, 'a': 0, 'emotionId': 0, 'p': 0}, 'userEmotion': {'d': 0, 'a': 0, 'emotionId': 10300, 'p': 0} } } '''运行结果:
E:python学习资料上课代码编写代码练习py>python e:/python学习资料/上课代码编写/代码练习py/图灵接口.py 叫我图灵机器人就可以了 E:python学习资料上课代码编写代码练习py>python e:/python学习资料/上课代码编写/代码练习py/图灵接口.py 人见人爱的图灵机器人,记住了吧~
二,电脑语音聊天:图灵接口结合百度云语音识别接口,
- 语音播报
- pyttsx3.init 初始化音频设备,然后播报
- 安装pip3 install pyttsx3
-
eg = init() #初始化音频设备
-
eg.say('hello,你好')
-
eg.runAndWait() #阅读
-
eg.close() #关闭设备
- 解决python提示No module named 'win32com'
- 安装下载对应的python系统位数的pywin32软件安装
- 地址:https://sourceforge.net/projects/pywin32/files/pywin32/
- 代码整合如下:
from 百度云 import * from 图灵接口 import * from pyttsx3 import init def main(): eg = init() while True: try: data = record_audio() question = baidu_fenxi(data) talk_str = tl_func(question) print(talk_str) eg.say(talk_str) eg.runAndWait() except KeyboardInterrupt: break if __name__ == '__main__': main()运行结果:(特别注意连个脚本要放在同一个目录下)
E:python学习资料上课代码编写代码练习py>python e:/python学习资料/上课代码编写/代码练习py/电脑聊天.py 你请我吃饭 一听就知道是人名。 好吃嘛!想吃! 没有一个 没有一个 你想说什么,慢慢说