import requests
import json
import time
def translate_text(text, source_lang="EN", target_lang="SV"):
url = "https://api.deeplx.org/translate"
payload = {
"source_lang": source_lang,
"target_lang": target_lang,
"text": text
}
response = requests.post(url, json=payload)
if response.status_code == 200:
return response.json()['data']
else:
return f"Translation failed: {response.status_code}"
def process_file(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
translated_lines = []
for line in lines:
if '=' in line:
key, value = line.strip().split('=', 1)
translated_value = translate_text(value)
# time.sleep(1)
translated_line = f"{key}={translated_value}\n"
translated_lines.append(translated_line)
else:
translated_lines.append(line)
with open(output_file, 'w', encoding='utf-8', errors='ignore') as f:
f.writelines(translated_lines)
# 使用示例
input_file = "D:\\IdeaProjects\\messages_en.properties"
output_file = 'messages_sv.properties'
process_file(input_file, output_file)
print(f"翻译完成。结果已保存到 {output_file}")
写一个python脚本读取文件,并翻译指定英文内容为瑞典语
于 2024-09-03 15:01:52 首次发布