百度翻译API调用

#百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系translate_api@baidu.com
# coding=utf-8

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

##APP ID:2020072400052563eight
##密钥:mZX6RZIZc5Y_zUW2XQbnine
##以上这两个参数,需要百度申请 ai.baidu.com

appid = ''  # 填写你的appidai.baidu.com
secretKey = ''  # 填写你的密钥

httpClient = None
myurl = '/api/trans/vip/translate'

fromLang = 'auto'   #原文语种
toLang = 'zh'   #译文语种
salt = random.randint(32768, 65536)
q= input("请输入要翻译的文本,例如:apple,I am a teacher")
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign

try:
    httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    httpClient.request('GET', myurl)

    # response是HTTPResponse对象
    response = httpClient.getresponse()
    result_all = response.read().decode("utf-8")
    result = json.loads(result_all)

    print (result)
        # result 输出结果如下:
        # {'from': 'en', 'to': 'zh', 'trans_result': [{'src': 'apple,I am a teacher', 'dst': '苹果,我是老师'}]}     
        # 结果写入文件中
    with open('fy.json','a') as f:
        f.write(result["trans_result"][0]["src"]+"\n")
        f.write(result["trans_result"][0]["dst"])

except Exception as e:
    print (e)
finally:
    if httpClient:
        httpClient.close()