python3调用百度翻译接口 百度翻译接口,普通版只能每秒调用一次,高级版的速度可以查看开发文档 百度翻译接口

APP ID 和密钥需要用户注册登录获得 填入APP ID 和密钥,就可运行 如果报错,检查第三方包是否安装

代码如下:

#/usr/bin/env python
#coding=utf8

import httplib
import md5
import urllib
import random

appid = '' #你的appid
secretKey = '' #你的密钥


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

sign = appid+q+str(salt)+secretKey
m1 = md5.new()
m1.update(sign)
sign = m1.hexdigest()
myurl = myurl+'?appid='+appid+'&q='+urllib.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()
    print response.read()
except Exception, e:
    print e
finally:
    if httpClient:
        httpClient.close()