我正在使用微软Azure翻译API来检测和翻译用户输入的语言,并将其翻译回英语。翻译后,我以JSON格式打印结果,可以在这里看到:https://i.sstatic.net/Zcq9l.png
之后,我试图打印’text:’之后的翻译内容,但每次尝试时都会遇到错误。我尝试使用for循环和引用它们,但不起作用。
这是代码片段:
path = '/translate'constructed_url = endpoint + pathparams = {'api-version': '3.0','to': ['en']}constructed_url = endpoint + pathheaders = {'Ocp-Apim-Subscription-Key': subscription_key,'Ocp-Apim-Subscription-Region': location,'Content-type': 'application/json','X-ClientTraceId': str(uuid.uuid4()) } user_input = input("You: ")body = [{ "text": user_input }]request = requests.post(constructed_url, params=params, headers=headers, json=body)response = request.json()json_data = json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(",", ": "))print(json_data)print("Translated Text: " + response.detectedLanguage.translations.text)
最后一行是导致错误的原因,但我不知道如何解决。如果有人能指导我,我将不胜感激。[1]: https://i.sstatic.net/Zcq9l.png
回答:
该对象是一个字典列表(在本例中只有一个)。如链接的图片所示。
在这种特定情况下,要访问翻译文本,你需要这样做:
response[0]["translations"]["text"]