使用python+百度翻译API翻译po文件

前言

本文介绍如何下载spigotmc插件脚本,并使用命令行运行。
提前准备Cookie

安装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)