Created
January 14, 2019 11:32
-
-
Save kaminomisosiru/f2b4941c6c6d634babd3dfc25d9a9988 to your computer and use it in GitHub Desktop.
This file contains 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
#coding:utf-8 | |
import urllib.request | |
import json | |
# トークン発行 | |
def get_access_token(key): | |
headers = { | |
'Ocp-Apim-Subscription-Key': key, | |
'Content-Length': 0 | |
}; | |
req = urllib.request.Request('https://api.cognitive.microsoft.com/sts/v1.0/issueToken', headers=headers, method='POST') | |
with urllib.request.urlopen(req) as res: | |
body = res.read() | |
return body.decode('utf-8') | |
# 翻訳実行 | |
def trenslator(text, _from, to, token): | |
headers = { | |
'Authorization': 'Bearer ' + token, | |
'Content-type': 'application/json' | |
} | |
url = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0" | |
url = url + '&to=' + to + '&from=' + _from | |
body = [{ | |
'text' : text | |
}] | |
req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method='POST') | |
with urllib.request.urlopen(req) as res: | |
response = res.read() | |
return json.loads(response.decode('utf-8'))[0]['translations'][0]['text'] | |
def main(): | |
api_key = '**********' #APIキー | |
text = '*****' #翻訳する文章 | |
_from = '**' #翻訳元の言語 | |
to = '**' #翻訳先の言語 | |
token = get_access_token(api_key) | |
print(trenslator(text, _from, to, token)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment