python调用百度翻译接口

来源:互联网 发布:ptc公司的软件 编辑:程序博客网 时间:2024/06/05 06:17

一、申请APIKey

到百度翻译开放平台申请APIKey,链接:http://api.fanyi.baidu.com/api/

二、关于生成链接

下面内容均整理自百度翻译开放平台接入文档。

这里写图片描述
返回结果是json格式,包含以下字段:
这里写图片描述

三、代码实例

1、先写一个能生产md5值的函数

import hashlibdef md5(str):#生成md5    m = hashlib.md5()    m.update(str)    return m.hexdigest()

2、英译中

def trans(src):#英译中    ApiKey = "xxxxxxxxxxxxxxxxx"    pwd = "***************"    salt = "1435660288"    all = ApiKey + src + salt + pwd    sign = md5(all)    src=src.replace(' ','+')#生成sign前不能替换    url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q="\          + src + "&from=en&to=zh&appid=" + ApiKey + \          "&salt=" + salt + "&sign=" + sign    try:        req = urllib2.Request(url)        con = urllib2.urlopen(req)        res = json.load(con)        if 'error_code' in res:            print 'error:', res['error_code']            return res['error_msg']        else:            dst = res['trans_result'][0]['dst']            return dst    except:        return "出错了"

3、中译英

def zh_to_en(src):#中译英    ApiKey = "xxxxxxxxxxxxxxxxx"    pwd = "***************"    salt = "1435660288"    all = ApiKey + src + salt + pwd    sign = md5(all)    src=src.replace(' ','+')#生成sign前不能替换    url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q="\          + src + "&from=zh&to=en&appid=" + ApiKey + \          "&salt=" + salt + "&sign=" + sign    try:        req = urllib2.Request(url)        con = urllib2.urlopen(req)        res = json.load(con)        if 'error_code' in res:            print 'error:', res['error_code']            return res['error_msg']        else:            dst = res['trans_result'][0]['dst']            return dst    except:        return "出错了"

完整代码见下:

#-*-coding:utf-8-*-import jsonimport urllib2import sysreload(sys)sys.setdefaultencoding('utf-8')import hashlibdef md5(str):#生成md5    m = hashlib.md5()    m.update(str)    return m.hexdigest()def trans(src):#英译中    ApiKey = "xxxxxxxxxxxxxxxxx"    pwd = "***************"    salt = "1435660288"    all = ApiKey + src + salt + pwd    sign = md5(all)    src=src.replace(' ','+')#生成sign前不能替换    url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q="\          + src + "&from=en&to=zh&appid=" + ApiKey + \          "&salt=" + salt + "&sign=" + sign    try:        req = urllib2.Request(url)        con = urllib2.urlopen(req)        res = json.load(con)        if 'error_code' in res:            print 'error:', res['error_code']            return res['error_msg']        else:            dst = res['trans_result'][0]['dst']            return dst    except:        return "出错了"def zh_to_en(src):#中译英    ApiKey = "xxxxxxxxxxxxxxxxx"    pwd = "***************"    salt = "1435660288"    all = ApiKey + src + salt + pwd    sign = md5(all)    src=src.replace(' ','+')#生成sign前不能替换    url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q="\          + src + "&from=zh&to=en&appid=" + ApiKey + \          "&salt=" + salt + "&sign=" + sign    try:        req = urllib2.Request(url)        con = urllib2.urlopen(req)        res = json.load(con)        if 'error_code' in res:            print 'error:', res['error_code']            return res['error_msg']        else:            dst = res['trans_result'][0]['dst']            return dst    except:        return "出错了"def main():    choice = raw_input("English to Chinese:Enter 1 \n"                      "Chinese to English:Enter 2 \n"                      "Enter:")    if choice == "1":        while True:            word = raw_input("Input the word you want to search:")            print "translate......"            target = en_to_zh(word)            print target    else:        while True:            word = raw_input("Input the word you want to search:")            print "translate......"            target = zh_to_en(word)            print targetif __name__ == '__main__':    main()