以下是使用百度翻译API实现全文翻译的示例代码(基于Python):
import requests
import hashlib
import random
import json
# 设置百度翻译API的参数
api_url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
app_id = 'your_app_id' # 替换为自己申请的App ID
secret_key = 'your_secret_key' # 替换为自己申请的Secret Key
# 要翻译的文本
text = 'Hello, world!'
# 生成随机数nonce和当前时间戳
nonce = random.randint(1, 10000)
timestamp = int(round(time.time() * 1000))
# 计算签名
sign_str = '{0}{1}{2}{3}'.format(app_id, text, str(nonce), str(timestamp) + secret_key)
md5 = hashlib.md5()
md5.update(sign_str.encode('utf-8'))
sign = md5.hexdigest()
# 发送POST请求翻译文本
response = requests.post(api_url, data={
'q': text,
'from': 'en', # 源语言,这里指英文
'to': 'zh', # 目标语言,这里指中文
'appid': app_id,
'salt': nonce,
'sign': sign,
})
# 解析返回的JSON数据
result = json.loads(response.text)
if 'error_code' in result:
print('翻译失败!错误码:{0},错误信息:{1}'.format(result['error_code'], result['error_msg']))
else:
print('翻译结果:{0}'.format(result['trans_result'][0]['dst']))
在实际使用时,需要替换代码中的`app_id`和`secret_key`为自己在百度翻译API平台申请的App ID和Secret Key。同时,还需要根据自己的需求修改源语言、目标语言和要翻译的文本。 |