使用 Python + 百度翻译 API 批量翻译 po 文件
用 Python 调百度翻译开放接口批量翻译 gettext 的 .po 文件:MD5 签名、分批请求、保留原有结构输出译文,带 tqdm 进度条。
前言
本文介绍如何用 Python 调用百度翻译开放接口,批量翻译 gettext 的 .po 文件:按行读取原文,用 appid + 盐 + appkey 生成 MD5 签名发起请求,再借 tqdm 显示进度条,把译文写入新文件。使用前需先到百度翻译开放平台申请 appid 和 appkey,并填入脚本末尾的配置区。
安装python环境
pip install tqdm
第一版
import requests
import random
import json
from hashlib import md5
from tqdm import tqdm # 导入 tqdm 库,用于显示进度条
def make_md5(s, encoding='utf-8'):
return md5(s.encode(encoding)).hexdigest()
def translate_po_file(input_file, output_file, from_lang, to_lang, appid, appkey):
# Set Baidu translation API endpoint
endpoint = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
# Generate salt for request
salt = random.randint(32768, 65536)
# Open input and output files
with open(input_file, 'r', encoding='utf-8') as fin, open(output_file, 'w', encoding='utf-8') as fout:
# Get total number of lines in the input file
total_lines = sum(1 for line in fin)
fin.seek(0) # Reset file pointer to beginning
for line in tqdm(fin, total=total_lines, desc='Translating'): # 使用 tqdm 包装循环
# Clean and prepare the line for translation
line = line.strip()
# Generate sign for the request
sign = make_md5(appid + line + str(salt) + appkey)
# Build the translation request payload
payload = {
'appid': appid,
'q': line,
'from': from_lang,
'to': to_lang,
'salt': salt,
'sign': sign
}
# Send translation request
response = requests.post(endpoint, params=payload)
translation_result = response.json()
# Extract translated text from the response
translated_text = translation_result.get('trans_result', [{}])[0].get('dst', line)
# Write translated text to the output file
fout.write(f'{translated_text}\n')
if __name__ == '__main__':
# Configuration
input_po_file = '' #翻译文件的路径
output_po_file = '' #翻译完保存的路径
from_lang = 'en' #翻译文件的语言
to_lang = 'zh' #翻译成什么语言
appid = '' #百度翻译API的appid
appkey = '' #百度翻译API的appkey
# Translate the PO file
translate_po_file(input_po_file, output_po_file, from_lang, to_lang, appid, appkey)
评论