加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
robot.py 1.85 KB
一键复制 编辑 原始数据 按行查看 历史
摸鱼怪 提交于 2019-10-21 18:03 . First Commit
import json
import urllib.request
def chat(question):
api_url = "http://openapi.tuling123.com/openapi/api/v2"
text_input = question
req = {
"reqType":0,
"perception":
{
"inputText":
{
"text": text_input
},
"selfInfo":
{
"location":
{
"city": "中山",
"province": "广东",
"street": ""
}
}
},
"userInfo":
{
"apiKey": "718da54d27f24596bd3bcd5220405baa",
"userId": "509847"
}
}
# 将字典格式的req转为utf8编码的字符串
req = json.dumps(req).encode('utf8')
print('\n' + '正在调用图灵机器人API...')
http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
response = urllib.request.urlopen(http_post)
print('得到回答,输出为字典格式:')
response_str = response.read().decode('utf8')
response_dic = json.loads(response_str)
intent_code = response_dic['intent']['code']
# 返回网页类的输出方式
if(intent_code == 10023):
results_url = response_dic['results'][0]['values']['url']
results_text = response_dic['results'][1]['values']['text']
answer = {"code": intent_code, "text": results_text, "url":results_url}
print(answer)
return(answer)
# 一般的输出方式
else:
results_text = response_dic['results'][0]['values']['text']
answer = {"code": intent_code, "text": results_text}
print(answer)
return(answer)
if __name__ == '__main__':
eg_question = {'text': '今天是几号', 'confidence': 0.9}
chat(eg_question)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化