Created
November 22, 2016 05:54
-
-
Save shivkanthb/c9ed9e4aff43a388ec58d2eef3fd1d51 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
import requests | |
import json | |
google_key = 'AIzaSyA-inA65SCHf-kT04GubUvTwCeGmPwikyQ' | |
base_url = 'https://www.googleapis.com/language/translate/v2' | |
# translates input to target_lang | |
def translate(input, target_lang='en'): | |
payload = {'q' : input, 'target' : target_lang, 'key' : google_key} | |
r = requests.get(base_url, params=payload) | |
d = json.loads(r.text) | |
try: | |
translated_text = d['data']['translations'][0]['translatedText'] | |
except: | |
translated_text = "ERROR" | |
return translated_text | |
# detects the language of the input and returns the 2 letter notation | |
def detect(input): | |
payload = {'q' : input, 'key' : google_key} | |
request_url = base_url + '/detect' | |
r = requests.get(request_url, params=payload) | |
d = json.loads(r.text) | |
try: | |
lang = d['data']['detections'][0][0]['language'] | |
except: | |
lang = "ERROR" | |
return lang | |
print translate("guten tag", 'en') | |
print detect("hello") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment