列表对象没有属性 'detectedLanguage'

List object has no attribute 'detectedLanguage'

我正在使用 Microsoft Azure Translator api 来检测和翻译用户输入的语言并将其翻译回英语。翻译后,我以 json 格式打印结果,可以在这里看到:https://i.stack.imgur.com/Zcq9l.png

之后,我试图打印在 'text:' 位之后翻译的任何内容,但是,每次我尝试这样做时,我总是收到错误消息。我尝试使用 for 循环并引用它们,但它不起作用。

这里是代码位:

path = '/translate'
constructed_url = endpoint + path

params = {
'api-version': '3.0',
'to': ['en']
}

constructed_url = endpoint + path

headers = {
'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.stack.imgur.com/Zcq9l.png

该对象是一个字典列表(在本例中只有一个)。如链接图片所示。

在这种特殊情况下,要获得翻译文本,您需要执行以下操作:

response[0]["translations"]["text"]