import os
import re
import requests
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(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
new_lines = []
for line in lines:
match = re.search(r'@SysLog\("([^|]+)\|([^"]+)"\)', line)
if match:
log_text = match.group(0)
if log_text.count('|') == 1:
original_text = match.group(2)
translated_text = translate_text(original_text)
time.sleep(0.5)
new_line = line.replace(f'|{original_text}', f'|{original_text}|{translated_text}')
new_lines.append(new_line)
else:
new_lines.append(line)
else:
new_lines.append(line)
with open(file_path, 'w', encoding='utf-8', errors='ignore') as f:
f.writelines(new_lines)
def process_directory(root_dir):
for subdir, _, files in os.walk(root_dir):
for file in files:
if file.endswith("Controller.java"):
file_path = os.path.join(subdir, file)
process_file(file_path)
print(f"Processed {file_path}")
root_directory = r'D:\IdeaProjects'
process_directory(root_directory)
print("处理完成。")