这个异常通常是由于传递给Microsoft Translator API的数据格式不正确引起的。下面是一个示例代码,演示了如何使用Microsoft Translator API,并处理可能出现的异常。
import requests
def translate_text(text, target_language):
subscription_key = 'YOUR_SUBSCRIPTION_KEY'
endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0'
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Region': 'YOUR_REGION'
}
data = [{
'text': text
}]
params = {
'api-version': '3.0',
'to': target_language
}
try:
response = requests.post(endpoint, headers=headers, params=params, json=data)
response.raise_for_status()
translation = response.json()[0]['translations'][0]['text']
return translation
except requests.exceptions.RequestException as error:
print('Error:', error)
except KeyError as error:
print('Invalid response:', error)
# 示例调用
try:
translated_text = translate_text('Hello', 'fr')
print(translated_text)
except Exception as error:
print('Translation failed:', error)
请确保将示例代码中的YOUR_SUBSCRIPTION_KEY
替换为您自己的Microsoft Translator API密钥,并将YOUR_REGION
替换为您的订阅区域。
下一篇:API 密钥未找到异常