Wednesday, 21 January 2009

Python Google Translate调用脚本

前一阵子一直想找一个命令行上的翻译程序,就自己写了一个Python程序:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import urllib2
import sys
import jsonlib
from optparse import OptionParser

URL = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%s&langpair=%s%%7C%s"

parser = OptionParser()
parser.add_option("-f", "--from", dest="lang1",
        help="The language code to translate from", default="en")
parser.add_option("-t", "--to", dest="lang2",
        help="The language code to translate to", default="zh")

(options, args) = parser.parse_args()
if len(args) < 1:
    print "Usage: python translate.py <translate text>"
    sys.exit(0)

text = ' '.join(args)
print "Translating %s from %s to %s" % (text, options.lang1, options.lang2)
query = (URL % (urllib.quote(text), options.lang1, options.lang2))
req = urllib2.Request(query)
req.add_header("Referer", "http://www.my-ajax-site.com")
r = urllib2.urlopen(req)

data = r.read()
obj = jsonlib.read(data)
if obj['responseStatus'] != 200L:
    print "Error: %s" % obj['responseDetails']
else:
    print "Translated text: %s" % obj['responseData']['translatedText']

No comments: