Created
March 12, 2014 13:49
-
-
Save zed/9507298 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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