- 1、python百度翻译爬虫
- 2、如何用python调用百度翻译
- 3、python语言翻译的过程是
- 4、Python有哪些好用的语言翻译方法
源页面获取的token必先向服务端post过后才有效果,sign是一层加密,token也是,源页面的id有效期长点,post过程用到了base64.encodebytes 以及 AES.CBC 加密等,我就知道这些,py调用js又会效率上不去
#/usr/bin/env python
#coding=utf8
import httplib
import md5
import urllib
import random
appid = ‘20151113000005349’
secretKey = ‘osubCEzlGjzvw8qdQc41’
httpClient = None
myurl = ‘/api/trans/vip/translate’
q = ‘apple’
fromLang = ‘en’
toLang = ‘zh’
salt = random.randint(32768, 65536)
sign = appid+q+str(salt)+secretKey
m1 = md5.new()
m1.update(sign)
sign = m1.hexdigest()
myurl = myurl+’?appid=’+appid+’q=’+urllib.quote(q)+’from=’+fromLang+’to=’+toLang+’salt=’+str(salt)+’sign=’+sign
try:
httpClient = httplib.HTTPConnection(‘api.fanyi.baidu.com’)
httpClient.request(‘GET’, myurl)
#response是HTTPResponse对象
response = httpClient.getresponse()
print response.read()
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
在调用百度翻译api之前,您需要申请开发者权限,获取APP ID及密钥。 一个账号只能获得一个APP ID和密钥。
参考价格:若当月翻译字符数≤2百万,免费;若超过2百万字符,按照49元/百万字符支付当月全部翻译字符数费用。
参考
“输入文本”—“翻译”—“得到译文”。详细步骤如下:
1、先输入文字。
2、首先调用两个需要到的第三方库,设置请求头,因为百度翻译反爬机制,经过观察只加密了sign数据,由代码计算,将js文件保存在根目录下。
3、设置data参数,获取cookies,发送 post请求,返回的是经过‘utf-8’编码后的字符串,我们要对其进行解码,并且转化为字典,直接对数据进行类型转换会报错“NameError: name ‘null’ is not defined”。
4、在数据(字典)中将我们要的结果提取出来。
1 import re
2 import urllib.parse, urllib.request
3 import hashlib
4 import urllib
5 import random
6 import json
7 import time
8 from translate import Translator
非python自带的库,如python google translator,需要手动安装,命令pip install module_name。
1. 百度翻译
1 appid = ‘your_appid’
2 secretKey = ‘your_secretKey’
3 url_baidu = ”
4
5 def translateBaidu(text, f=’ja’, t=’zh’):
6 salt = random.randint(32768, 65536)
7 sign = appid + text + str(salt) + secretKey
8 sign = hashlib.md5(sign.encode()).hexdigest()
9 url = url_baidu + ‘?appid=’ + appid + ‘q=’ + urllib.parse.quote(text) + ‘from=’ + f + ‘to=’ + t + \
10 ‘salt=’ + str(salt) + ‘sign=’ + sign
11 response = urllib.request.urlopen(url)
12 content = response.read().decode(‘utf-8’)
13 data = json.loads(content)
14 result = str(data[‘trans_result’][0][‘dst’])
15 print(result)
参数:text–待翻文本,f–初始语言,t–目标语言,后面方法类似。
2. 有道翻译
1 url_youdao = ‘;smartresult=rulesmartresult=ugcsessionFrom=’ \
2 ”
3 dict = {}
4 dict[‘type’] = ‘AUTO’
5 dict[‘doctype’] = ‘json’
6 dict[‘xmlVersion’] = ‘1.8’
7 dict[‘keyfrom’] = ‘fanyi.web’
8 dict[‘ue’] = ‘UTF-8’
9 dict[‘action’] = ‘FY_BY_CLICKBUTTON’
10 dict[‘typoResult’] = ‘true’
11
12 def translateYoudao(text):
13 global dict
14 dict[‘i’] = text
15 data = urllib.parse.urlencode(dict).encode(‘utf-8’)
16 response = urllib.request.urlopen(url_youdao, data)
17 content = response.read().decode(‘utf-8’)
18 data = json.loads(content)
19 result = data[‘translateResult’][0][0][‘tgt’]
20 print(result)
参数主要由字典dict指定,发现没有地方可以指定语言(可能是我没找到),测试结果是不管输入什么语言的文本,输出均是中文。
3. 谷歌翻译
1 url_google = ”
2 reg_text = re.compile(r'(?=TRANSLATED_TEXT=).*?;’)
3 user_agent = r’Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ‘ \
4 r’Chrome/44.0.2403.157 Safari/537.36′
5
6 def translateGoogle(text, f=’ja’, t=’zh-cn’):
7 values = {‘hl’: ‘zh-cn’, ‘ie’: ‘utf-8’, ‘text’: text, ‘langpair’: ‘%s|%s’ % (f, t)}
8 value = urllib.parse.urlencode(values)
9 req = urllib.request.Request(url_google + ‘?’ + value)
10 req.add_header(‘User-Agent’, user_agent)
11 response = urllib.request.urlopen(req)
12 content = response.read().decode(‘utf-8’)
13 data = reg_text.search(content)
14 result = data.group(0).strip(‘;’).strip(‘\”)
15 print(result)
和上面两种方法一样,采用的是访问网页的形式来进行翻译。
还有一种是利用python谷歌翻译模块Translator:
1 def translateGoogle2(text):
2 result = translator.translate(text)
3 print(result)
4. 测试代码
测试过程:
翻译5个字串为一个小的单位,输出消耗时间;
循环10次为一个大的单位,输出消耗时间;
对不同的语言字串和循环次数做过多次测试,发现情况基本类似,所以这里选择了10次。
1 text_list = [‘こんにちは’, ‘こんばんは’, ‘おはようございます’, ‘お休(やす)みなさい’, ‘お元気(げんき)ですか’]
2
3 time_baidu = 0
4 time_youdao = 0
5 time_google = 0
6 time_google2 = 0
7
8 for i in list(range(1, 11)):
9 time1 = time.time()
10 for text in text_list:
11 translateBaidu(text)
12 time2 = time.time()
13 print(‘百度翻译第%s次时间:%s’ % (i, time2 – time1))
14 time_baidu += (time2 – time1)
15
16 time1 = time.time()
17 for text in text_list:
18 translateYoudao(text)
19 time2 = time.time()
20 print(‘有道翻译第%s次时间:%s’ % (i, time2 – time1))
21 time_youdao += (time2 – time1)
22
23 time1 = time.time()
24 for text in text_list:
25 translateGoogle(text)
26 time2 = time.time()
27 print(‘谷歌翻译第%s次时间:%s’ % (i, time2 – time1))
28 time_google += (time2 – time1)
29
30 time1 = time.time()
31 for text in text_list:
32 translateGoogle2(text)
33 time2 = time.time()
34 print(‘谷歌2翻译第%s次时间:%s’ % (i, time2 – time1))
35 time_google2 += (time2 – time1)
36
37
38 print(‘百度翻译时间:%s’ % (time_baidu / 10))
39 print(‘有道翻译时间:%s’ % (time_youdao / 10))
40 print(‘谷歌翻译时间:%s’ % (time_google / 10))
41 print(‘谷歌2翻译时间:%s’ % (time_google2 / 10))
原创文章,作者:FRDCP,如若转载,请注明出处:https://www.506064.com/n/127303.html