Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

66 lines (50 sloc) 1.862 kB
#!/usr/bin/python
import urllib2
import sys
import argparse
import json
DEST_LANG="fr"
SOURCE_LANG="en"
def pull(phrase, source, dest):
phrase = urllib2.quote(phrase)
try:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open("http://translate.google.co.uk" + "/translate_a/t?client=webapp&sl=" + source + "&tl=" + dest + "&hl=en&sc=1&q=" + phrase)
except urllib2.HTTPError, err:
print "ERROR [" + err + "] Google says no"
sys.exit(-1)
except:
print "ERROR [UNKNOWN] Google really says no"
sys.exit(-2)
return json.loads(response.read())
def parse(reply):
tran = ""
for s in reply['sentences']:
tran+=s['trans']
return tran
def main():
parser = argparse.ArgumentParser(description='A command line wrapper for Google Translate')
parser.add_argument('text', nargs='+', help='Profanities you would like to translate')
parser.add_argument('-s', default=SOURCE_LANG, metavar="source_lang", help="Language you know")
parser.add_argument('-d', default=DEST_LANG, metavar="dest_lang", help="Language you wish you knew")
parser.add_argument('--switch', '-w', action='store_true', help="Switch the default languages")
parser.add_argument('--log', '-l', metavar="log_file", help="Log to [file]")
args = parser.parse_args()
colour="\033[1;91m" # Red
colour_default="\033[0;39m"
original = ' '.join(args.text)
if (args.switch is False):
colour="\033[1;34m" # Blue
args.s, args.d = args.d, args.s
translation = parse(pull(original, args.d, args.s))
if (args.log != None):
try:
fd = open(args.log, 'a')
except:
print "ERROR [FAILED TO OPEN FILE]"
sys.exit(-3);
fd.write(original + " -> " + translation + "\n")
print colour + translation + colour_default
if __name__ == '__main__':
main()
Jump to Line
Something went wrong with that request. Please try again.