python3.7.4 百度翻译api

发布时间:2019-10-16 17:29:36编辑:auto阅读(2691)

    import random
    import hashlib
    import http.client, urllib.parse
    import json
    class baidu_trans:
        # 接口地址
        domain = 'api.fanyi.baidu.com'
        uri = "/api/trans/vip/translate"
        # 密钥相关
        app_id = ""
        app_screct = ""
        salt = random.randint(32768, 65536)
        # 错误码
        errors_code = {
            "52000": "成功",
            "52001": "请求超时",
            "52002": "系统错误",
            "52003": "未授权用户",
            "54000": "必填参数为空",
            "54001": "签名错误",
            "54003": "访问频率受限",
            "54004": "账户余额不足",
            "54005": "长query请求频繁",
            "58000": "客户端IP非法",
            "58001": "译文语言方向不支持",
            "58002": "服务当前已关闭",
            "90107": "认证未通过或未生效",
        }
        # 生成签名
        def getSign(self,context):
            sign = self.app_id + context + str(self.salt) + self.app_screct
            md5_obj = hashlib.md5()
            md5_obj.update(sign.encode('utf-8'))
            return md5_obj.hexdigest()
            pass
        # 将文本翻译为指定的语言
        def trans(self,context):
            httpClient = None
            form = {
                "q": context,
                "from": "en",
                "to": "zh",
                "appid": self.app_id,
                "salt": self.salt,
                "sign": self.getSign(context),
            }
            try:
                url = self.uri + '?appid=' + form["appid"] + '&q=' + urllib.parse.quote(form["q"]) + '&from=' + form["from"] + '&to=' + form["to"] + '&salt=' + str(form["salt"]) + '&sign=' + form['sign']
                httpClient = http.client.HTTPConnection(self.domain)
                httpClient.request('GET', url)
                response = httpClient.getresponse()
                result = json.loads(bytes.decode(response.read()))
                if 'error_code' in result:
                    print('错误'+result["error_code"]+':' + self.errors_code[result["error_code"]] )
                return result["trans_result"][0]['dst']
            except Exception as e:
                print(e)
            finally:
                if httpClient:
                    httpClient.close()
            pass
        pass

关键字