-
Notifications
You must be signed in to change notification settings - Fork 1
/
DictionaryExample.py
43 lines (34 loc) · 1.57 KB
/
DictionaryExample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# -*- coding: utf-8 -*-
# This simple app uses the '/dictionary/examples' resource to illustrate
# how terms in a dictionary are contexutalized.
# 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 = '6e212400769e4218b93a53e51f3893cf'
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-dictionary-examples
path = '/dictionary/examples?api-version=3.0'
params = '&from=en&to=fr';
constructed_url = endpoint + path + params
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# Each object takes two key/value pairs: 'text' and 'translation'.
# Note: You can pass more than one object in body.
body = [{
'text': 'great',
'translation': 'formidable'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ': ')))