之前用python2和wxpython写过一个,到现在都基本忘完了,这次用python3写个命令行的。
#coding=UTF-8
import urllib.request
import urllib.parse
import json
import argparse
'''
************************************
@FileName : Google Translator
@Author : auo
@Description : 模拟浏览器POST表单提交实现谷歌翻译
@link : http://my.oschina.net/auo
************************************
'''
languages = ['zh-CN', 'en', 'de', 'ja', 'ru', 'fr']
class GoogleTranslator(object) :
def __init__(self) :
self.userAgent = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36'}
self.requestUrl = 'http://translate.google.com.hk/translate_a/t'
self.requestMethod = 'POST'
def requestForTranslate(self, typeDestination, textSource) :
userAgent = self.userAgent
requestUrl = self.requestUrl
requestMethod = self.requestMethod
values = {'client' : 'a', 'sl' : 'auto', 'tl' : typeDestination, 'hl' : 'zh-CN', 'ie' : 'UTF-8', 'oe' : 'UTF-8', 'q' : textSource}
data = urllib.parse.urlencode(values).encode('UTF-8')
request = urllib.request.Request(url = requestUrl, data = data, headers = userAgent, method = requestMethod)
try :
textDestination = json.loads(urllib.request.urlopen(request).read().decode('utf-8'))
sentences = textDestination['sentences']
num = 0
trans = ''
while num < len(sentences) :
trans += sentences[num]['trans']
num += 1
print(trans)
except :
print('翻译失败')
exit()
def main(self) :
parser = argparse.ArgumentParser(description = 'This is a description of %(prog)s', formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-l', '--lang', dest = 'typeDestination', help = '译文语种', default = 'en')
parser.add_argument('-t', '--text', dest = 'textSource', help = '待译原文', required = True, nargs = '+')
args = parser.parse_args()
if args.typeDestination not in languages :
print('尚不支持该语种')
exit()
typeDestination = args.typeDestination
textSource = ''
for text in args.textSource :
textSource += text
textSource += ' '
self.requestForTranslate(typeDestination, textSource)
if __name__ == '__main__' :
translator = GoogleTranslator()
translator.main()
来源:oschina
链接:https://my.oschina.net/u/1391727/blog/222202