当前位置: 移动技术网 > 移动技术>移动开发>Android > 百度翻译接口调用实例

百度翻译接口调用实例

2020年07月08日  | 移动技术网移动技术  | 我要评论
百度接口启用地址:https://api.fanyi.baidu.com/ 创建自己的翻译项目,并注意保留APPID和密钥# 中文翻译成英文def translate_t(myurl,httpClient,q_t): fromLang = 'auto' #原文语种[自动检测] toLang = 'en' #译文语种[英语] salt = random.randint(32768, 65536) sign = appid + q_t + str(salt) +.

百度接口启用地址:https://api.fanyi.baidu.com/  创建自己的翻译项目,并注意保留APPID和密钥

# 中文翻译成英文
def translate_t(myurl,httpClient,q_t):
    fromLang = 'auto'   #原文语种[自动检测]
    toLang = 'en'   #译文语种[英语]
    salt = random.randint(32768, 65536)
    sign = appid + q_t + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl1 = myurl + '?appid=' + appid + '&q=' + parse.quote(q_t) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
    salt) + '&sign=' + sign
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl1)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        jg = (result['trans_result'][0]['dst'])
    except Exception as e:
        print(e)
        jg = '接口请求出错'
    finally:
        if httpClient:
            httpClient.close()
    return jg


# 英文翻译成中文
def translate_f(myurl, httpClient,q_f):
    fromLang = 'auto'  # 原文语种[自动检测]
    toLang = 'zh'  # 译文语种[中文]
    salt = random.randint(32768, 65536)
    sign = appid + q_f + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl1 = myurl + '?appid=' + appid + '&q=' + parse.quote(q_f) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
        salt) + '&sign=' + sign
    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl1)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        jg = (result['trans_result'][0]['dst'])
    except Exception as e:
        print(e)
        jg = '接口请求出错'
    finally:
        if httpClient:
            httpClient.close()
    return jg


if __name__ == '__main__':
    i = ''  # 需要翻译的字符串
    if 'img' not in i and i != '':
        appid = '20200707000514536'  # 填写你的appid
        secretKey = '2T7OTcmi3V2slOlGYQfR'  # 填写你的密钥
        httpClient = None
        myurl = '/api/trans/vip/translate'
        q_t = i.replace('<p>','')
        q_f = translate_t(myurl,httpClient,q_t)
        print(q_f)
        sleep(5)
        jg = translate_f(myurl,httpClient,q_f)
        sleep(5)
        print('<p>' + jg)
        news.append('<p>' + jg)
    else:
       news.append(i)

 

本文地址:https://blog.csdn.net/mjp_erhuo/article/details/107191781

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网