6 from urllib.request import urlopen, Request
7 from urllib.parse import urlencode
8 from argparse import ArgumentParser
12 sys.stderr.write((msg % args) + '\n')
16 def translate(text, dst_lang, src_lang='auto'):
30 url = 'http://translate.google.com/translate_a/t'
31 data = ('client=t&' + urlencode(dict(text=text)) + '&hl=en&' +
32 urlencode(dict(sl=src_lang)) + '&' +
33 urlencode(dict(tl=dst_lang)) +
34 '&multires=1&otf=2&pc=1&ssel=0&tsel=0&sc=1')
35 headers = { 'User-agent': 'Mozilla/5.0' }
37 req = Request(url=url, data=data.encode('utf-8'), headers=headers)
38 page = urlopen(req).read().decode('utf-8')
39 # attempt to fix invalid json (will break translated text that had ,,+)
40 page = re.sub(',,+', ',', page)
43 result = json.loads(page)
44 except Exception as e:
45 die("Error parsing results: %s", e)
47 return ''.join((c[0] for c in result[0]))
51 parser = ArgumentParser(description='Translate text using '
53 parser.add_argument('--from','-f', dest='from_', metavar='LANG',
55 help='Translate from LANG language '
56 '(e.g. en, de, es, default: auto)')
57 parser.add_argument('--to', '-t', metavar='LANG', default='en',
58 help='Translate to LANG language '
59 '(e.g. en, de, es, default: en)')
60 parser.add_argument('--input-file', '-i', metavar='FILE',
61 help='Get text to translate from FILE instead of stdin')
62 parser.add_argument('--output-file', '-o', metavar='FILE',
63 help='Output translated text to FILE instead of stdout')
64 parser.add_argument('--input-encoding', '-I', metavar='ENC',
65 help='Use ENC caracter encoding to read the input '
66 '(default: get from locale)')
67 parser.add_argument('--output-encoding', '-O', metavar='ENC',
68 help='Use ENC caracter encoding to write the output '
69 '(default: get from locale)')
71 args = parser.parse_args()
73 args.input = sys.stdin
76 args.input = open(args.input_file)
77 except Exception as e:
78 die("Can't open file %s for reading: %s",
81 args.output = sys.stdout
84 args.output = open(args.output_file, 'w')
85 except Exception as e:
86 die("Can't open file %s for writing: %s",
93 if args.input_encoding:
94 text = args.input.buffer.read().decode(args.input_encoding)
96 text = args.input.read()
97 trans_text = translate(text, args.to, args.from_) + '\n'
98 if args.input_encoding:
99 args.output.buffer.write(trans_text.encode(args.input_encoding))
101 args.output.write(trans_text)