鱼C论坛

 找回密码
 立即注册
查看: 2835|回复: 1

[已解决]找了个百度api翻译,有时会出错,谁能debug下?

[复制链接]
发表于 2022-11-30 22:10:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
zhihu_hot50_cn-BAIDUtrans2-en.zip (2.37 KB, 下载次数: 3)

zhihu_hot50_cn.txt (31.5 KB, 下载次数: 3)

2个问题,

1.只能翻译几行?
2.原文件的换行,翻译后就不换行了


或者有好用的   百度api全文翻译  代码,请推荐下
最佳答案
2023-4-5 11:27:37
以下是使用百度翻译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。同时,还需要根据自己的需求修改源语言、目标语言和要翻译的文本。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-4-5 11:27:37 | 显示全部楼层    本楼为最佳答案   
以下是使用百度翻译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。同时,还需要根据自己的需求修改源语言、目标语言和要翻译的文本。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-23 23:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表