88 lines
3.2 KiB
Python
88 lines
3.2 KiB
Python
import os
|
|
import json
|
|
from collections import defaultdict
|
|
|
|
def should_ignore(line):
|
|
"""檢查這行是不是要跳過不處理的(比如註解或特殊標記)"""
|
|
line = line.strip()
|
|
return line.startswith(("@", ">", ".", "END")) or line == ""
|
|
|
|
def collect_all_texts(root_path):
|
|
"""從所有子目錄收集需要翻譯的文本"""
|
|
# 使用defaultdict自動初始化三種文本類別
|
|
all_data = {
|
|
'normal': defaultdict(dict),
|
|
'special': defaultdict(dict),
|
|
'namedesc': defaultdict(dict)
|
|
}
|
|
|
|
# 遍歷所有目錄和文件
|
|
for dirpath, _, filenames in os.walk(root_path):
|
|
# 跳過translate目錄本身
|
|
if "translate" in dirpath.split(os.sep):
|
|
continue
|
|
|
|
for filename in filenames:
|
|
if not filename.endswith(".txt"):
|
|
continue
|
|
|
|
file_path = os.path.join(dirpath, filename)
|
|
# 計算相對路徑作為分類依據
|
|
relative_path = os.path.relpath(dirpath, root_path)
|
|
|
|
with open(file_path, "r", encoding="utf-8") as f:
|
|
lines = f.readlines()
|
|
|
|
for line_num, line in enumerate(lines):
|
|
stripped = line.strip()
|
|
if should_ignore(stripped):
|
|
continue
|
|
|
|
# 生成包含路徑的唯一鍵值
|
|
full_key = f"{relative_path}/{filename}__{line_num}"
|
|
|
|
# 分類處理不同類型文本
|
|
if stripped.startswith(("name:", "desc:", "menuDesc:")):
|
|
idx = stripped.find(":")
|
|
all_data['namedesc'][relative_path][full_key] = stripped[idx+1:].strip()
|
|
elif stripped.startswith("*"):
|
|
all_data['special'][relative_path][full_key] = stripped
|
|
else:
|
|
all_data['normal'][relative_path][full_key] = stripped
|
|
|
|
return all_data
|
|
|
|
def save_centralized_json(data, root_path):
|
|
"""將合併後的翻譯文件保存到根目錄的translate資料夾"""
|
|
translate_dir = os.path.join(root_path, "translate")
|
|
os.makedirs(translate_dir, exist_ok=True)
|
|
|
|
# 合併並保存三種類型文件
|
|
for file_type in ['normal', 'special', 'namedesc']:
|
|
merged = {}
|
|
# 將不同目錄的內容合併到單一字典
|
|
for dir_path, content in data[file_type].items():
|
|
merged.update(content)
|
|
|
|
if merged:
|
|
file_name = f"translation_{file_type}.json"
|
|
file_path = os.path.join(translate_dir, file_name)
|
|
with open(file_path, "w", encoding="utf-8") as f:
|
|
json.dump(merged, f, ensure_ascii=False, indent=2)
|
|
print(f"✔ 已生成合併翻譯文件:{file_name}")
|
|
|
|
def walk_and_process(root="."):
|
|
"""主處理流程"""
|
|
print(f"🔍 開始掃描根目錄:{os.path.abspath(root)}")
|
|
|
|
# 收集所有文本資料
|
|
all_texts = collect_all_texts(root)
|
|
|
|
# 保存合併後的翻譯文件
|
|
save_centralized_json(all_texts, root)
|
|
|
|
print("\n🏁 已完成所有文本收集!")
|
|
print(f"📁 翻譯文件統一存放於:{os.path.join(root, 'translate')}")
|
|
|
|
if __name__ == "__main__":
|
|
walk_and_process() |