- 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/zh-tw/n/127303.html