百度 api

推荐博客 : https://www.cnblogs.com/adam012019/p/11441461.html

 

代码:

import json
import random
import hashlib
from urllib import parse
import http.client

class BaiduTranslate:
    def __init__(self,fromLang,toLang):
        self.url = "/api/trans/vip/translate"
        self.appid="20220112001053714"
        self.secretKey = 'E8mi7L9bVyeGSAJUVVP4'
        self.fromLang = fromLang
        self.toLang = toLang
        self.salt = random.randint(32768, 65536)

    def BdTrans(self,text):
        sign = self.appid + text + str(self.salt) + self.secretKey
        md = hashlib.md5()
        md.update(sign.encode(encoding='utf-8'))
        sign = md.hexdigest()
        myurl = self.url + \
                '?appid=' + self.appid + \
                '&q=' + parse.quote(text) + \
                '&from=' + self.fromLang + \
                '&to=' + self.toLang + \
                '&salt=' + str(self.salt) + \
                '&sign=' + sign
        try:
            httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
            httpClient.request('GET', myurl)
            response = httpClient.getresponse()
            html = response.read().decode('utf-8')
            html = json.loads(html)
            dst = html["trans_result"][0]["dst"]
            return  True , dst
        except Exception as e:
            return False , e

if __name__=='__main__':
    BaiduTranslate_test = BaiduTranslate('zh','en')
    Results = BaiduTranslate_test.BdTrans("逻辑学")#要翻译的词组
    print(Results)

  

posted @ 2022-01-12 17:19  楼主好菜啊  阅读(113)  评论(0编辑  收藏  举报