python 百度翻译接口调用

def youdaotranslate(list_str,APP_KEY,APP_SECRET):
    httpClient = None
    myurl = '/api/trans/vip/translate'
    fromLang = 'zh'  # 原文语种
    toLang = 'vie'  # 译文语种
    salt = random.randint(32768, 65536)
    sign = APP_KEY + list_str + str(salt) + APP_SECRET
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + APP_KEY + '&q=' + urllib.parse.quote(list_str) + '&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)
        zidian = []#返回字典类型
        for v in result['trans_result']:
            zidian.append(v['dst'])
        return zidian

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()
发布了8 篇原创文章 · 获赞 1 · 访问量 102
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览