百度翻譯API使用(中文翻譯爲英文)

使用方法:
首先,訪問百度翻譯官網

開通通用翻譯API服務,獲取對應的appid,secretKey,並將其填入函數對應位置。
API調用函數定義以下json

import requests 
import hashlib
import random
appid = 'xxx'  # appid
secretKey ='yyy' # 密鑰

def baidu_fanyi(query):
    fanyi_text = ""
    try:
        salt = random.randint(1, 10000)  # 隨機數
        code = appid + query + str(salt) + secretKey
        sign = hashlib.md5(code.encode()).hexdigest()  # 簽名
        api = "http://api.fanyi.baidu.com/api/trans/vip/translate"
        data = {
            "q": query,
            "from": "zh",
            "to": "en",
            "appid": appid,
            "salt": salt,
            "sign": sign
        }
        response = requests.post(api, data)
        result = response.json()
        # result是一個包含翻譯信息的字典
        # query若是包含換行符,將會出現多個返回結果
        ret = result.get("trans_result")
        for i in ret:
            fanyi_text = fanyi_text +"\n"+i.get("dst")
        error_code = "ok"
    except Exception as e:
        error_code = result["error_code"]
        fanyi_text = None
    finally:
        return fanyi_text, error_code

函數調用方法以下api

# 返回值爲fanyi_text:翻譯結果,error_code:錯誤代碼,可參考官方文檔定位問題。
fanyi_text, error_code = baidu_fanyi(ori_text)
相關文章
相關標籤/搜索