Python 调用百度翻译API

949次阅读
没有评论
import json
import random
import requests
import urllib.parse
from hashlib import md5



def translate_api(text):
    appid = '20211104000991497'
    secretKey = 'xAJH4EpPKHoaYYRNGEr2'
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    q = text
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint(32768, 65536)
    sign = appid+q+str(salt)+secretKey
    m1 = md5()
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()
    myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    return myurl

def fanyi_zh(text):

    myurl = translate_api(text)
    response = requests.get(myurl)
    rans_result = json.loads(response.text)['trans_result'][0]['dst']
    return rans_result

if __name__ == '__main__':
    i = fanyi_zh("Moody autumn day in the Dolomites forest and mountains")
    print(i)

希望能帮助大家!!!

原创面具网

1
liuze
版权声明:本站原创文章,由 liuze2022-01-25发表,共计752字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
载入中...