Last active
October 11, 2016 11:00
-
-
Save mmas/d196b94a1021171c4c9e21f4cdb15a2e to your computer and use it in GitHub Desktop.
Google translate client
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/python | |
""" | |
Google translate client | |
usage: python translate.py [-h] [-v] [-ua User-Agent] source_lang target_lang text | |
positional arguments: | |
source_lang | |
target_lang | |
text | |
optional arguments: | |
-h, --help show this help message and exit | |
-v, --verbose | |
-ua User-Agent, --useragent User-Agent | |
default="Mozilla/5.0" | |
""" | |
import argparse | |
import re | |
import urllib | |
import urllib2 | |
BASE_URL = 'https://translate.google.com/translate_a/single' | |
DEFAULT_UA = 'Mozilla/5.0' | |
WEB_URL = 'https://translate.google.com/#{source_lang}/{target_lang}/{text}' | |
parser = argparse.ArgumentParser(description='Google translate client') | |
parser.add_argument('source_lang') | |
parser.add_argument('target_lang') | |
parser.add_argument('text') | |
parser.add_argument('-v', '--verbose', action='store_true') | |
parser.add_argument('-ua', '--useragent', | |
default=DEFAULT_UA, | |
metavar='User-Agent', | |
help='default="%s"' % DEFAULT_UA) | |
args = parser.parse_args() | |
url = '%s?%s' % (BASE_URL, urllib.urlencode({'client': 'gtx', | |
'sl': args.source_lang, | |
'tl': args.target_lang, | |
'dt': 't', | |
'q': args.text})) | |
opener = urllib2.build_opener() | |
opener.addheaders = [('User-Agent', args.useragent)] | |
resp = opener.open(url) | |
raw_resp = resp.read() | |
result = re.match(r'\[\[\[(.*)\]\]', raw_resp).group(1).split(',') | |
result = re.sub(r'"', '', result[0]) | |
if args.verbose: | |
print 'result=%s' % result | |
print 'url=%s' % url | |
print 'user-agent=%s' % args.useragent | |
print 'status=%s' % resp.getcode() | |
print 'response=%s' % raw_resp | |
print 'web=%s' % WEB_URL.format(source_lang=args.source_lang, | |
target_lang=args.target_lang, | |
text=urllib.quote(args.text)) | |
else: | |
print result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment