python - 微软用python翻译?
问题描述
我正在使用默认的 Microsoft python 库来翻译文本,但每次我尝试它都会出错
# -*- coding: utf-8 -*-
# This simple app uses the '/translate' resource to translate text from
# one language to another.
# This sample runs on Python 2.7.x and Python 3.x.
# You may need to install requests and uuid.
# Run: pip install requests uuid
import os, requests, uuid, json
key_var_name = 'TRANSLATOR_TEXT_SUBSCRIPTION_KEY'
if not key_var_name in os.environ:
raise Exception('Please set/export the environment variable: {}'.format(key_var_name))
subscription_key = os.environ[key_var_name]
endpoint_var_name = 'TRANSLATOR_TEXT_ENDPOINT'
if not endpoint_var_name in os.environ:
raise Exception('Please set/export the environment variable: {}'.format(endpoint_var_name))
endpoint = os.environ[endpoint_var_name]
# If you encounter any issues with the base_url or path, make sure
# that you are using the latest endpoint: https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate
path = '/translate?api-version=3.0'
params = '&from=en&to=de&to=it'
constructed_url = endpoint + path + params
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text' : 'Hello World!'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': ')))
添加 azure 提供的密钥和端点后,我得到了这个错误
Traceback (most recent call last):
File "C:\Users\seto\Codes\Python\translation\main.py", line 14, in <module>
raise Exception('Please set/export the environment variable: {}'.format(key_var_name))
Exception: Please set/export the environment variable:
解决方案
我设法通过删除环境变量并仅使用局部变量来解决它
# -*- coding: utf-8 -*-
# This simple app uses the '/translate' resource to translate text from
# one language to another.
# This sample runs on Python 2.7.x and Python 3.x.
# You may need to install requests and uuid.
# Run: pip install requests uuid
import os, requests, uuid, json
key_var_name = 'XXXXXXXXXXXXXXX'
subscription_key = key_var_name
endpoint_var_name = 'https://api.cognitive.microsofttranslator.com/'
endpoint = endpoint_var_name
# If you encounter any issues with the base_url or path, make sure
# that you are using the latest endpoint: https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate
path = '/translate?api-version=3.0'
params = '&from=en&to=ar'
constructed_url = endpoint + path + params
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': "francecentral",
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text' : 'Hello World!'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()