将Watson Assistant的答案传递给变量Python

问题描述 投票:1回答:1

我试图将Watson Assistant的输出变为变量。因此,就我搜索而言,我需要得到json的“输出”和“文本”部分(首先它是一个字典,但后来我们将它解析为json)。但我似乎无法得到它:

我已经在这两个问题中搜索过:This one for watson This one for parsing the json

代码非常简单:访问我的机器人,输入“行程”。我已经取出了api和工作区,但我有它们(显然)。

if __name__ == '__main__':
    assistant = watson_developer_cloud.AssistantV1(

        iam_apikey='{YOUR API HERE}',
        version='2018-09-20',
        url='https://gateway-syd.watsonplatform.net/assistant/api'
    )

    response = assistant.message(
        workspace_id='{YOUR WORKSPACE HERE}',
        input={
            'text': 'trips'
        }
    ).get_result()
    fullResponse=json.dumps(response, indent=2)
    print(fullResponse)
    print("testing to print the output: ")
    respuesta=json.dumps(response, indent=2)
    #print(respuesta['output'][0]['text'])
    print(respuesta['output']['text'])

并输出:

Traceback (most recent call last):
  "intents": [
  File "C:/Users/.PyCharmCE2018.3/config/scratches/pruebaMain.py", line 105, in <module>
    {
    print(respuesta['output']['text'])
      "intent": "trips",
TypeError: string indices must be integers
      "confidence": 1
    }
  ],
  "entities": [],
  "input": {
    "text": "trips"
  },
  "output": {
    "generic": [
      {
        "response_type": "text",
        "text": "We got trips to different countries! Type continents to know more!"
      }
    ],
    "text": [
      "We got trips to different countries! Type continents to know more!"
    ],
    "nodes_visited": [
      "node_2_1544696932582"
    ],
    "log_messages": []
  },
  "context": {
    "conversation_id": "{took it out for privacy}",
    "system": {
      "initialized": true,
      "dialog_stack": [
        {
          "dialog_node": "root"
        }
      ],
      "dialog_turn_counter": 1,
      "dialog_request_counter": 1,
      "_node_output_map": {
        "node_2_1544696932582": {
          "0": [
            0
          ]
        }
      },
      "branch_exited": true,
      "branch_exited_reason": "completed"
    }
  }
}
testing to print the output: 

Process finished with exit code 1

所以我想得到答案“我们到不同的国家旅行!输入各大洲了解更多!”。我已经阅读了python API的文档和更多信息(https://github.com/IBM-Cloud/watson-conversation-variables),但似乎找不到任何东西。我也试过用$but访问json变量不起作用。

python ibm-cloud watson-conversation
1个回答
4
投票

你不必在这里使用json.dumps,你可以直接使用从服务返回的响应JSON,如下面的代码片段所示

import watson_developer_cloud

if __name__ == '__main__':
    assistant = watson_developer_cloud.AssistantV1(

        iam_apikey='APIKEY',
        version='2018-09-20',
        url='https://gateway.watsonplatform.net/assistant/api'
    )

    response = assistant.message(
        workspace_id='WORKSPACE_ID',
        input={
            'text': 'trips'
        }
    ).get_result()

    print(response)
    print(response['output']['text'][0])
© www.soinside.com 2019 - 2024. All rights reserved.