多翻譯引擎的程式

SilenceHL發表於2021-06-11

最近有很多翻譯的需求,於是寫了一個支援多翻譯引擎的程式,目前支援百度、有道與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())
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章