Created
November 9, 2012 06:55
-
-
Save lintianzhi/4044131 to your computer and use it in GitHub Desktop.
parse Google translate for convenient query
This file contains 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 | |
#coding=utf-8 | |
import urllib | |
import urllib2 | |
import sys | |
import simplejson | |
values_t = {'client':'t', | |
'hl':'zh_CN', | |
'ie':'UTF-8', | |
'multries':2, | |
'oe':'UTF-8', | |
'otf':2, | |
'sc':1, | |
'sl':'en', | |
'ssel':0, | |
'text':'hello', | |
'tl':'zh-CN', | |
'tsel':0} | |
headers = {'Host':'translate.google.cn', | |
'Referer':'http://translate.google.cn/', | |
'User-Agent':' Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0'} | |
url_t = 'http://translate.google.cn/translate_a/t' | |
url_ex = 'http://translate.google.cn/translate_a/ex' | |
def parse(data): | |
lst = data.split(',') | |
for i,v in enumerate(lst): | |
if not v: | |
lst[i] = '0' | |
data = ','.join(lst) | |
vl = simplejson.loads(data) | |
return vl | |
def query(arg): | |
# query for your input | |
if 96<ord(arg[0])<123 or 64<ord(arg[0])<91: | |
values_t['sl'],values_t['tl'] = ('en','zh-CN') | |
else: | |
values_t['sl'],values_t['tl'] = ('zh-CN','en') | |
values_t['text'] = arg | |
para = urllib.urlencode(values_t) | |
req = urllib2.Request(url_t,para,headers) | |
f = urllib2.urlopen(req) | |
result = parse(f.read()) | |
trans_rst = result[0][0][0].encode('utf-8') | |
print 'Translate Result:' | |
print trans_rst | |
#query_ex(arg, trans_rst) | |
def query_ex(arg, trans_rst): | |
# query for example | |
values_ex = {'q':arg, | |
'sl':values_t['sl'], | |
'tl':values_t['tl'], | |
'utrans':trans_rst} | |
para = urllib.urlencode(values_ex) | |
req = urllib2.Request(url_ex,para,headers) | |
f = urllib2.urlopen(req) | |
try: | |
usage_ex = simplejson.loads(f.read())[1][0] | |
print '\nUsage Example:' | |
for j,ex in enumerate(usage_ex): | |
for i in [0,3]: | |
ex[i] = ex[i].replace('<b>','|') | |
ex[i] = ex[i].replace('</b>','|"') | |
ex[i] = ex[i].encode('utf-8') | |
print '{0}:\n{1}\n{2}'.format(j,ex[0],ex[3]) | |
except IndexError: | |
pass | |
def main(): | |
arg = ' '.join(sys.argv[1:]) | |
if arg: | |
query(arg) | |
return | |
while True: | |
arg = sys.stdin.readline() | |
query(arg) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment