我正在尝试从dialogflow获取直接文本响应 . 我从github上的示例代码中得到答案,但这根本不是用户友好的 . 我怎样才能获得“仅限语音”的回复?
import os.path
import sys
try:
import apiai
except ImportError:
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
import apiai
CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'
def main():
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.lang = 'de' # optional, default value equal 'en'
request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"
request.query = "Hello"
response = request.getresponse()
print (response.read())
if __name__ == '__main__':
main()
我只期待一个简单的结果 . 一个简单的问候文本 .
我得到的是= b'{\n "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n "timestamp": "2017-12-05T22:18:15.563Z",\n "lang": "en",\n "result": {\n "source": "agent",\n "resolvedQuery": "hi",\n "action": "input.welcome",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {\n "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n "webhookUsed": "false",\n "webhookForSlotFillingUsed": "false",\n "intentName": "Default Welcome Intent"\n },\n "fulfillment": {\n "speech": "Hi there!",\n "messages": [\n {\n "type": 0,\n "speech": "Hi there!"\n }\n ]\n },\n "score": 1.0\n },\n "alternateResult": {\n "source": "domains",\n "resolvedQuery": "hi",\n "action": "smalltalk.greetings.hello",\n "actionIncomplete": false,\n "parameters": {},\n "contexts": [],\n "metadata": {},\n "fulfillment": {\n "speech": "Hey!",\n "source": "agent"\n },\n "score": 1.0\n },\n "status": {\n "code": 200,\n "errorType": "success",\n "webhookTimedOut": false\n },\n "sessionId": "mr.9000"\n}'
2 回答
试试这样就可以得到这样的信息:
别忘了添加
在开始 . 如果尚未安装,请安装它 . 如果你想在python中处理json,你将不得不这样做 . 告诉我它是否有效
看起来你正在使用Dialogflow's query API . 响应的格式记录在here中 . 你必须解析JSON . 最常见的方法是......
使用您需要导入的
json
模块(即文件顶部的import json
) .接下来'll need to load the JSON string you'收到加载方法(即在定义
response
后添加一行:response_dict = json.loads(response.read())
最后,您需要从
response_dict
对象中检索正确的字符串:print(response_dict.['result']['resolvedQuery'])