如何用Python语言调取百度翻译的API

诸神缄默不语-个人CSDN博文目录

本文介绍如何用Python语言调用百度翻译的API服务。
理论上类似的写法也可以应用于其他语言。

http://api.fanyi.baidu.com/manage/developer可以注册开发者,或者APP ID和秘钥;然后还可以进行开发者认证,获得更多免费额度。

对于文中MD5加密的相关代码可参考我之前撰写的另一篇博文:Python如何实现MD5加密

1. 通用翻译

在这里插入图片描述
开发者认证后就是高级版。

通用翻译API接入文档
语言的代码也可以在↑网址中搜到。

get版:

import random,hashlib,requests

salt=random.randint(0,100000)

APP_ID=''
API_KEY=''

api_https='https://fanyi-api.baidu.com/api/trans/vip/translate'

query='本文使用ROUGE-1、ROUGE-2和ROUGE-L的F1值作为评估指标,分别计算以字为gram粒度和以词为gram粒度的结果,实验证明了本文提出的模型在所有指标上均高于基线模型。'
str1=str(APP_ID)+query+str(salt)+API_KEY
md=hashlib.md5()
md.update(str1.encode('utf-8'))
sign=md.hexdigest()

response1=requests.get(api_https+'?q='+query+'&from=zh&to=en&appid='+APP_ID+'&salt='+str(salt)+'&sign='+md.hexdigest())
print(response1.json())

输出:{'from': 'zh', 'to': 'en', 'trans_result': [{'src': '本文使用ROUGE-1、ROUGE-2和ROUGE-L的F1值作为评估指标,分别计算以字为gram粒度和以词为gram粒度的结果,实验证明了本文提出的模型在所有指标上均高于基线模型。', 'dst': 'This article uses the F1 values of ROUGE-1, ROUGE-2, and ROUGE-L as evaluation indicators, and calculates the results of word based grain size and word based grain size, respectively. The experiment proves that the proposed model is higher than the baseline model in all indicators.'}]}

post版:
待补

2. 垂直领域翻译

在这里插入图片描述

垂直领域API接入文档

在这里我用的是academic学术论文领域。

get版:

import random,hashlib,requests

salt=random.randint(0,100000)

APP_ID=''
API_KEY=''

api_https='https://fanyi-api.baidu.com/api/trans/vip/fieldtranslate'
domain='academic'

query='本文使用ROUGE-1、ROUGE-2和ROUGE-L的F1值作为评估指标,分别计算以字为gram粒度和以词为gram粒度的结果,实验证明了本文提出的模型在所有指标上均高于基线模型。'
str1=str(APP_ID)+query+str(salt)+domain+API_KEY
md=hashlib.md5()     #获取一个md5加密算法对象
md.update(str1.encode('utf-8'))
sign=md.hexdigest()

response1=requests.get(api_https+'?q='+query+'&from=zh&to=en&appid='+APP_ID+'&salt='+str(salt)+'&domain='+domain+'&sign='+md.hexdigest())
print(response1.json())

输出:{'from': 'zh', 'to': 'en', 'trans_result': [{'src': '本文使用ROUGE-1、ROUGE-2和ROUGE-L的F1值作为评估指标,分别计算以字为gram粒度和以词为gram粒度的结果,实验证明了本文提出的模型在所有指标上均高于基线模型。', 'dst': 'This paper uses the F1 value of rouge-1, rouge-2 and rouge-l as the evaluation index, and calculates the results of the word as gram granularity and the word as gram granularity respectively. Experiments show that the model proposed in this paper is higher than the baseline model in all indicators.'}]

好像比通用版的好了点?不确定

post版:
待补

报错信息示例:

  1. {'error_code': '54001', 'error_msg': 'Invalid Sign'}(不知道为啥会有这个bug,我是跑了一串代码只有少数几次会报这个错)

3. 文档翻译

待补。

  1. 【应用】PHP调用百度文档翻译接口_百度翻译文档回调_林坤源的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/PolarisRisingWar/article/details/130972511