Skip to content

Instantly share code, notes, and snippets.

@zed
Created March 12, 2014 13:49
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zed/9507298 to your computer and use it in GitHub Desktop.
Save zed/9507298 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""Translate text_to_translate using microsoft translator service."""
import json
import xml.etree.ElementTree as etree
try:
from urllib import urlencode
from urllib2 import urlopen, Request
except ImportError: # Python 3
from urllib.parse import urlencode
from urllib.request import urlopen, Request
text_to_translate = 'hello world'
# provide credentials
# http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx
# http://msdn.microsoft.com/en-us/library/hh454950.aspx
client_id, client_secret = open('credentials').read().split()
# get access token
data = urlencode(dict(
grant_type='client_credentials',
client_id=client_id,
client_secret=client_secret,
scope='http://api.microsofttranslator.com')).encode('ascii')
r = urlopen("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13", data)
token = json.loads(r.read().decode('utf-8'))
# translate
req = Request("https://api.microsofttranslator.com/v2/Http.svc/Translate?" +
urlencode({'text': text_to_translate, 'from': 'en', 'to': 'ko'}),
headers={"Authorization": "Bearer " + token['access_token']})
response = urlopen(req)
print(etree.parse(response).getroot().text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment