pythonartificial-intelligencemicrosoft-translator

List object has no attribute 'detectedLanguage'


I'm using microsoft azure translator api to detect and translate the language the user is inputting and translating it back to english. After translating it, I'm printing the results in json format, which can be seen here: https://i.sstatic.net/Zcq9l.png

Afterwards, I'm trying to print whatever is translated after the 'text:' bit, however, I keep getting an error each time I try to do so. I tried using a for loop and referencing them, but it doesn't work.

Here is the code bit:

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)

The final line is what's causing the error, but I'm not sure how to resolve it. I would appreciate if someone can guide me accordingly. [1]: https://i.sstatic.net/Zcq9l.png


Solution

  • The object is a List of Dictionaries (just one in this case). As seen in the linked image.

    In this particular case, to reach the translation text, you need to do:

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