Python3调谷歌翻译

公司最近有翻译的需求(本人适用的是在第三方服务器上使用,不在本地也不在谷歌控制台),发现Google的Translate API只能FQ调,但是国内也有翻译需求,经多方查找汇集众家之长,找到一个感觉最好用的,稍稍改进了一下,

一。国内爬虫版(主要参考https://blog.csdn.net/andeyeluguo/article/details/78581590):

很多博客有提到tk值要js处理,不多说,直接上干货

首先,是要pip处理js的模块  

pip install PyExecJS

创建HandleJs.py

 1 import execjs  
 2   
 3 class Py4Js():  
 4       
 5     def __init__(self):  
 6         self.ctx = execjs.compile(""" 
 7         function TL(a) { 
 8         var k = ""; 
 9         var b = 406644; 
10         var b1 = 3293161072; 
11          
12         var jd = "."; 
13         var $b = "+-a^+6"; 
14         var Zb = "+-3^+b+-f"; 
15      
16         for (var e = [], f = 0, g = 0; g < a.length; g++) { 
17             var m = a.charCodeAt(g); 
18             128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), 
19             e[f++] = m >> 18 | 240, 
20             e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, 
21             e[f++] = m >> 6 & 63 | 128), 
22             e[f++] = m & 63 | 128) 
23         } 
24         a = b; 
25         for (f = 0; f < e.length; f++) a += e[f], 
26         a = RL(a, $b); 
27         a = RL(a, Zb); 
28         a ^= b1 || 0; 
29         0 > a && (a = (a & 2147483647) + 2147483648); 
30         a %= 1E6; 
31         return a.toString() + jd + (a ^ b) 
32     }; 
33      
34     function RL(a, b) { 
35         var t = "a"; 
36         var Yb = "+"; 
37         for (var c = 0; c < b.length - 2; c += 3) { 
38             var d = b.charAt(c + 2), 
39             d = d >= t ? d.charCodeAt(0) - 87 : Number(d), 
40             d = b.charAt(c + 1) == Yb ? a >>> d: a << d; 
41             a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d 
42         } 
43         return a 
44     } 
45     """)  
46           
47     def getTk(self,text):  
48         return self.ctx.call("TL",text)

创建main.py

 1 import json
 2 import urllib.request
 3 import urllib.parse
 4 from HandleJs import Py4Js
 5 
 6 
 7 def open_url(url):
 8     headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
 9     req = urllib.request.Request(url=url, headers=headers)
10     response = urllib.request.urlopen(req)
11     data = response.read().decode('utf-8')
12     return data
13 
14 
15 def buildUrl(content, tk, tl):
16     baseUrl = 'http://translate.google.cn/translate_a/single'
17     baseUrl += '?client=t&'
18     baseUrl += 'sl=auto&'
19     baseUrl += 'tl=' + str(tl) + '&'
20     baseUrl += 'hl=zh-CN&'
21     baseUrl += 'dt=at&'
22     baseUrl += 'dt=bd&'
23     baseUrl += 'dt=ex&'
24     baseUrl += 'dt=ld&'
25     baseUrl += 'dt=md&'
26     baseUrl += 'dt=qca&'
27     baseUrl += 'dt=rw&'
28     baseUrl += 'dt=rm&'
29     baseUrl += 'dt=ss&'
30     baseUrl += 'dt=t&'
31     baseUrl += 'ie=UTF-8&'
32     baseUrl += 'oe=UTF-8&'
33     baseUrl += 'clearbtn=1&'
34     baseUrl += 'otf=1&'
35     baseUrl += 'pc=1&'
36     baseUrl += 'srcrom=0&'
37     baseUrl += 'ssel=0&'
38     baseUrl += 'tsel=0&'
39     baseUrl += 'kc=2&'
40     baseUrl += 'tk=' + str(tk) + '&'
41     baseUrl += 'q=' + content
42     return baseUrl
43 
44 
45 def translate(content, tk, tl):
46     content = urllib.parse.quote(content)
47     url = buildUrl(content, tk, tl)
48 
49     result = open_url(url)
50     res_json = json.loads(result)
51     trans_text = res_json[0][0][0]
52     # sl是要翻译的源语种
53     sl = res_json[8][0][0]
54     print(trans_text)
55     print(sl)
56 
57 
58 def main():
59     js = Py4Js()
60     #content是要翻译的内容
61     #tl是要翻译的目标语种,值参照ISO 639-1标准,如果翻译成中文"zh/zh-CN简体中文"
62     content = "test"
63     tl = "ja"
64     tk = js.getTk(content)
65     translate(content, tk, tl)
66 
67 
68 if __name__ == "__main__":
69     main()

 二。谷歌API调用

谷歌控制台创建项目,绑定信用卡(翻译API收费),绑定项目和账号,启用Translation API,创建service account(这部分可以参考 https://blog.csdn.net/nicolelili1/article/details/76973097 的一-五),然后

首先还是pip Google translation SDK

pip install --upgrade google-cloud-translate

翻译的代码(指定credentials)

1 from google.cloud import translate
2     from google.oauth2 import service_account
3     credentials = service_account.Credentials.from_service_account_file('Key.json')
4 translate_client = translate.Client(credentials=credentials) 5 translation = translate_client.translate( 6 text, 7 target_language=target_lang) 8 print(translation)

ok啦

 三。谷歌API调用

转了一大圈,发现自己走了很多弯路,此方法最为便捷,但是也有安全隐患(有明文的Key)

代码

1 import urllib.request
2 import urllib.parse
3 key = "**********" #你的API Key
4 content = urllib.parse.quote(text)
5 url = "https://translation.googleapis.com/language/translate/v2?key=%s&target=%s&q=%s" % (key, target_lang, content)
6 response = urllib.request.urlopen(url)
7 data = json.loads(response.read().decode('utf-8'))
8 res = data['data']['translations'][0]
9 print(res)

 附AWS的翻译(不过目前只有3个region有这个功能):

1 import boto3
2 client = boto3.client('translate', region_name='us-east-1')
3 result = client.translate_text(
4     Text=text,
5     SourceLanguageCode=source_lang if source_lang else 'auto',
6     TargetLanguageCode=target_lang
7 )

 

参考链接:

https://blog.csdn.net/andeyeluguo/article/details/78581590

https://blog.csdn.net/nicolelili1/article/details/76973097

https://cloud.google.com/translate/docs/quickstart-client-libraries

https://googleapis.github.io/google-cloud-python/latest/translate/usage.html

http://iamct.iteye.com/blog/952558

posted @ 2018-12-05 12:51  sen_c7  阅读(1794)  评论(0编辑  收藏  举报