Skip to content

Commit 1a7ddac

Browse files
author
Jann Skotdal
authored
Merge pull request #4 from erhopf/master
Updating and standardizing Python samples for Translator Text
2 parents 41374b5 + 986b045 commit 1a7ddac

File tree

9 files changed

+258
-226
lines changed

9 files changed

+258
-226
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Operating System files
2+
.DS_Store
3+
.gitignore
4+
Thumbs.db

BreakSentence.py

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,44 @@
11
# -*- coding: utf-8 -*-
22

3-
import http.client, urllib.parse, uuid, json
4-
5-
# **********************************************
6-
# *** Update or verify the following values. ***
7-
# **********************************************
8-
9-
# Replace the subscriptionKey string value with your valid subscription key.
10-
subscriptionKey = 'ENTER KEY HERE'
11-
12-
host = 'api.cognitive.microsofttranslator.com'
3+
# This simple app uses the '/breaksentence' resource to identify the source
4+
# language and determines the numbe of characters in each sentence.
5+
6+
# This sample runs on Python 2.7.x and Python 3.x.
7+
# You may need to install requests and uuid.
8+
# Run: pip install requests uuid
9+
10+
11+
import os, requests, uuid, json
12+
13+
# Checks to see if the Translator Text subscription key is available
14+
# as an environment variable. If you are setting your subscription key as a
15+
# string, then comment these lines out.
16+
if 'TRANSLATOR_TEXT_KEY' in os.environ:
17+
subscriptionKey = os.environ['TRANSLATOR_TEXT_KEY']
18+
else:
19+
print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
20+
exit()
21+
# If you want to set your subscription key as a string, uncomment the next line.
22+
#subscriptionKey = 'put_your_key_here'
23+
24+
# If you encounter any issues with the base_url or path, make sure
25+
# that you are using the latest endpoint: https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-break-sentence
26+
base_url = 'https://api.cognitive.microsofttranslator.com'
1327
path = '/breaksentence?api-version=3.0'
14-
15-
params = ''
16-
17-
text = 'How are you? I am fine. What did you do today?'
18-
19-
def breakSentences (content):
20-
21-
headers = {
22-
'Ocp-Apim-Subscription-Key': subscriptionKey,
23-
'Content-type': 'application/json',
24-
'X-ClientTraceId': str(uuid.uuid4())
25-
}
26-
27-
conn = http.client.HTTPSConnection(host)
28-
conn.request ("POST", path + params, content, headers)
29-
response = conn.getresponse ()
30-
return response.read ()
31-
32-
requestBody = [{
33-
'Text' : text,
28+
params = '&language=en'
29+
constructed_url = base_url + path + params
30+
31+
headers = {
32+
'Ocp-Apim-Subscription-Key': subscriptionKey,
33+
'Content-type': 'application/json',
34+
'X-ClientTraceId': str(uuid.uuid4())
35+
}
36+
37+
# You can pass more than one object in body.
38+
body = [{
39+
'text': 'How are you? I am fine. What did you do today?'
3440
}]
35-
content = json.dumps(requestBody, ensure_ascii=False).encode('utf-8')
36-
result = breakSentences (content)
37-
38-
# Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
39-
# We want to avoid escaping any Unicode characters that result contains. See:
40-
# https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
41-
output = json.dumps(json.loads(result), indent=4, ensure_ascii=False)
41+
request = requests.post(constructed_url, headers=headers, json=body)
42+
response = request.json()
4243

43-
print (output)
44+
print(json.dumps(response, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ': ')))

Detect.py

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,43 @@
11
# -*- coding: utf-8 -*-
22

3-
import http.client, urllib.parse, uuid, json
4-
5-
# **********************************************
6-
# *** Update or verify the following values. ***
7-
# **********************************************
8-
9-
# Replace the subscriptionKey string value with your valid subscription key.
10-
subscriptionKey = 'ENTER KEY HERE'
11-
12-
host = 'api.cognitive.microsofttranslator.com'
3+
# This simple app uses the '/detect' resource to identify the language of
4+
# the provided text or texts.
5+
6+
# This sample runs on Python 2.7.x and Python 3.x.
7+
# You may need to install requests and uuid.
8+
# Run: pip install requests uuid
9+
10+
11+
import os, requests, uuid, json
12+
13+
# Checks to see if the Translator Text subscription key is available
14+
# as an environment variable. If you are setting your subscription key as a
15+
# string, then comment these lines out.
16+
if 'TRANSLATOR_TEXT_KEY' in os.environ:
17+
subscriptionKey = os.environ['TRANSLATOR_TEXT_KEY']
18+
else:
19+
print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
20+
exit()
21+
# If you want to set your subscription key as a string, uncomment the next line.
22+
#subscriptionKey = 'put_your_key_here'
23+
24+
# If you encounter any issues with the base_url or path, make sure
25+
# that you are using the latest endpoint: https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect
26+
base_url = 'https://api.cognitive.microsofttranslator.com'
1327
path = '/detect?api-version=3.0'
28+
constructed_url = base_url + path
1429

15-
params = ''
16-
17-
text = 'Salve, mondo!'
30+
headers = {
31+
'Ocp-Apim-Subscription-Key': subscriptionKey,
32+
'Content-type': 'application/json',
33+
'X-ClientTraceId': str(uuid.uuid4())
34+
}
1835

19-
def detect (content):
20-
21-
headers = {
22-
'Ocp-Apim-Subscription-Key': subscriptionKey,
23-
'Content-type': 'application/json',
24-
'X-ClientTraceId': str(uuid.uuid4())
25-
}
26-
27-
conn = http.client.HTTPSConnection(host)
28-
conn.request ("POST", path, content, headers)
29-
response = conn.getresponse ()
30-
return response.read ()
31-
32-
requestBody = [{
33-
'Text' : text,
36+
# You can pass more than one object in body.
37+
body = [{
38+
'text': 'Salve, mondo!'
3439
}]
35-
content = json.dumps(requestBody, ensure_ascii=False).encode('utf-8')
36-
result = detect (content)
37-
38-
# Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
39-
# We want to avoid escaping any Unicode characters that result contains. See:
40-
# https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
41-
output = json.dumps(json.loads(result), indent=4, ensure_ascii=False)
40+
request = requests.post(constructed_url, headers=headers, json=body)
41+
response = request.json()
4242

43-
print (output)
43+
print(json.dumps(response, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ': ')))

DictionaryExample.py

Lines changed: 40 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,46 @@
11
# -*- coding: utf-8 -*-
22

3-
import http.client, urllib.parse, uuid, json
4-
5-
# **********************************************
6-
# *** Update or verify the following values. ***
7-
# **********************************************
8-
9-
# Replace the subscriptionKey string value with your valid subscription key.
10-
subscriptionKey = 'ENTER KEY HERE'
11-
12-
host = 'api.cognitive.microsofttranslator.com'
3+
# This simple app uses the '/dictionary/examples' resource to illustrate
4+
# how terms in a dictionary are contexutalized.
5+
6+
# This sample runs on Python 2.7.x and Python 3.x.
7+
# You may need to install requests and uuid.
8+
# Run: pip install requests uuid
9+
10+
11+
import os, requests, uuid, json
12+
13+
# Checks to see if the Translator Text subscription key is available
14+
# as an environment variable. If you are setting your subscription key as a
15+
# string, then comment these lines out.
16+
if 'TRANSLATOR_TEXT_KEY' in os.environ:
17+
subscriptionKey = os.environ['TRANSLATOR_TEXT_KEY']
18+
else:
19+
print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
20+
exit()
21+
# If you want to set your subscription key as a string, uncomment the next line.
22+
#subscriptionKey = 'put_your_key_here'
23+
24+
# If you encounter any issues with the base_url or path, make sure
25+
# that you are using the latest endpoint: https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-examples
26+
base_url = 'https://api.cognitive.microsofttranslator.com'
1327
path = '/dictionary/examples?api-version=3.0'
14-
1528
params = '&from=en&to=fr';
16-
17-
text = 'great'
18-
translation = 'formidable'
19-
20-
def examples (content):
21-
22-
headers = {
23-
'Ocp-Apim-Subscription-Key': subscriptionKey,
24-
'Content-type': 'application/json',
25-
'X-ClientTraceId': str(uuid.uuid4())
26-
}
27-
28-
conn = http.client.HTTPSConnection(host)
29-
conn.request ("POST", path + params, content, headers)
30-
response = conn.getresponse ()
31-
return response.read ()
32-
33-
requestBody = [{
34-
'Text' : text,
35-
'Translation' : translation,
29+
constructed_url = base_url + path + params
30+
31+
headers = {
32+
'Ocp-Apim-Subscription-Key': subscriptionKey,
33+
'Content-type': 'application/json',
34+
'X-ClientTraceId': str(uuid.uuid4())
35+
}
36+
37+
# Each object takes two key/value pairs: 'text' and 'translation'.
38+
# Note: You can pass more than one object in body.
39+
body = [{
40+
'text': 'great',
41+
'translation': 'formidable'
3642
}]
37-
content = json.dumps(requestBody, ensure_ascii=False).encode('utf-8')
38-
result = examples (content)
39-
40-
# Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
41-
# We want to avoid escaping any Unicode characters that result contains. See:
42-
# https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
43-
output = json.dumps(json.loads(result), indent=4, ensure_ascii=False)
43+
request = requests.post(constructed_url, headers=headers, json=body)
44+
response = request.json()
4445

45-
print (output)
46+
print(json.dumps(response, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ': ')))

DictionaryLookup.py

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,44 @@
11
# -*- coding: utf-8 -*-
22

3-
import http.client, urllib.parse, uuid, json
4-
5-
# **********************************************
6-
# *** Update or verify the following values. ***
7-
# **********************************************
8-
9-
# Replace the subscriptionKey string value with your valid subscription key.
10-
subscriptionKey = 'ENTER KEY HERE'
11-
12-
host = 'api.cognitive.microsofttranslator.com'
3+
# This simple app uses the '/dictionary/lookup' resource to return alternative
4+
# translations for a word and a small number of idiomatic phrases.
5+
6+
# This sample runs on Python 2.7.x and Python 3.x.
7+
# You may need to install requests and uuid.
8+
# Run: pip install requests uuid
9+
10+
11+
import os, requests, uuid, json
12+
13+
# Checks to see if the Translator Text subscription key is available
14+
# as an environment variable. If you are setting your subscription key as a
15+
# string, then comment these lines out.
16+
if 'TRANSLATOR_TEXT_KEY' in os.environ:
17+
subscriptionKey = os.environ['TRANSLATOR_TEXT_KEY']
18+
else:
19+
print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
20+
exit()
21+
# If you want to set your subscription key as a string, uncomment the next line.
22+
#subscriptionKey = 'put_your_key_here'
23+
24+
# If you encounter any issues with the base_url or path, make sure
25+
# that you are using the latest endpoint: https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup
26+
base_url = 'https://api.cognitive.microsofttranslator.com'
1327
path = '/dictionary/lookup?api-version=3.0'
14-
15-
params = '&from=en&to=fr';
16-
17-
text = 'great'
18-
19-
def lookup (content):
20-
21-
headers = {
22-
'Ocp-Apim-Subscription-Key': subscriptionKey,
23-
'Content-type': 'application/json',
24-
'X-ClientTraceId': str(uuid.uuid4())
25-
}
26-
27-
conn = http.client.HTTPSConnection(host)
28-
conn.request ("POST", path + params, content, headers)
29-
response = conn.getresponse ()
30-
return response.read ()
31-
32-
requestBody = [{
33-
'Text' : text,
28+
params = '&from=en&to=es';
29+
constructed_url = base_url + path + params
30+
31+
headers = {
32+
'Ocp-Apim-Subscription-Key': subscriptionKey,
33+
'Content-type': 'application/json',
34+
'X-ClientTraceId': str(uuid.uuid4())
35+
}
36+
37+
# You can pass more than one object in body.
38+
body = [{
39+
'text': 'Elephants'
3440
}]
35-
content = json.dumps(requestBody, ensure_ascii=False).encode('utf-8')
36-
result = lookup (content)
37-
38-
# Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
39-
# We want to avoid escaping any Unicode characters that result contains. See:
40-
# https://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence
41-
output = json.dumps(json.loads(result), indent=4, ensure_ascii=False)
41+
request = requests.post(constructed_url, headers=headers, json=body)
42+
response = request.json()
4243

43-
print (output)
44+
print(json.dumps(response, sort_keys=True, indent=4, ensure_ascii=False, separators=(',', ': ')))

0 commit comments

Comments
 (0)