yyq
12/21/2017 - 3:03 AM

百度翻译api示例代码

百度翻译api示例代码

#!/usr/bin/python
# -*- coding: utf-8 -*-

"""readme

this script is python 3 only

please config your own appid and secretKey, refer link: http://api.fanyi.baidu.com/api/trans/product/index

usage command: python translate-baidu-api.py word.txt

translate result will be stdout line by line

"""

import http.client as httplib
import hashlib
import urllib
import random
import sys

def translate(transchar):

    appid = 'xxxxxxxxxxxxx'
    secretKey = 'yyyyyyyyyyyy'

    httpClient = None
    myurl = '/api/trans/vip/translate'
    q = transchar
    fromLang = 'zh'
    toLang = 'en'
    salt = random.randint(32768, 65536)

    sign = appid+q+str(salt)+secretKey
    # m1 = md5.new()
    # m1.update(sign)
    # sign = m1.hexdigest()
    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 = httplib.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)

        # response是HTTPResponse对象
        response = httpClient.getresponse()
        answer = response.read().decode("utf-8")
        # print(type(answer))
        answer = answer.split('dst')[1]
        answer = answer.replace('\"', '')
        answer = answer.replace(':', '')
        answer = answer.replace('}', '')
        answer = answer.replace(']', '')
        return transchar + "#===#" + answer

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


with open(sys.argv[1]) as f:
    for word in f:
        print(translate(word.strip()))