最近有很多翻译的需求,于是写了一个支持多翻译引擎的程序,目前支持百度、有道与Google,由于国内没有Google,暂不提供Google引擎。
import sys
import time
import uuid
import random
import hashlib
import requests
from hashlib import md5
from importlib import reload
class AggregateTranslation(object):def __init__(self, query, lang_type):
self.lang_type_dict = {'中文': 'zh','英语': 'en','日语': 'jp','韩语': 'kor',}if lang_type not in self.lang_type_dict.keys():raise Exception('需要翻译的语种还未支持或语种名不正确')
self.query = query
self.lang_type = lang_type
def baidu(self):"""
百度翻译引擎
:return:
"""
app_id = '应用ID'
app_key = '应用密钥'
endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path
salt = random.randint(32768, 65536)
sign = md5((app_id + self.query + str(salt) + app_key).encode('utf-8')).hexdigest()
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': app_id, 'q': self.query, 'from': 'auto', 'to': self.lang_type_dict[self.lang_type],'salt': salt,'sign': sign}
response = requests.post(url, params=payload, headers=headers)return response.json()['trans_result'][0]['dst']
def youdao(self):"""
有道翻译引擎
:return:
"""
lang_type_dict = self.lang_type_dict
lang_type_dict['中文'] = 'zh - CHS'reload(sys)
app_id = '应用ID'
app_key = '应用密钥'
data = {}
data['from'] = 'auto'
data['to'] = lang_type_dict[self.lang_type]
data['signType'] = 'v3'
curtime = str(int(time.time()))
data['curtime'] = curtime
salt = str(uuid.uuid1())if self.query is None:return None
size = len(self.query)
truncate = self.query if size <= 20 else self.query[0:10] + str(size) + self.query[size - 10:size]
signStr = app_id + truncate + salt + curtime + app_key
hash_algorithm = hashlib.sha256()
hash_algorithm.update(signStr.encode('utf-8'))
sign = hash_algorithm.hexdigest()
data['appKey'] = app_id
data['q'] = self.query
data['salt'] = salt
data['sign'] = sign
data['vocabId'] = "用户词表ID"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post('https://openapi.youdao.com/api', data=data, headers=headers)
err_code = response['errorCode']if err_code == 0:return response['translation']else:raise Exception("翻译错误,错误代码为:{}".format(err_code))
if __name__ == '__main__':print(AggregateTranslation('人生苦短,我用Python', '英语').baidu())