83 lines
3.4 KiB
Python
83 lines
3.4 KiB
Python
import os
|
||
import json
|
||
|
||
def should_ignore(line):
|
||
"""檢查這行是不是要跳過不處理的(比如註解或特殊標記)"""
|
||
line = line.strip()
|
||
return line.startswith(("@", ">", ".", "END")) or line == ""
|
||
|
||
def collect_texts_from_txt(path):
|
||
"""從目錄下的所有txt檔案裡收集需要翻譯的文字"""
|
||
normal_texts = {} # 存普通對話文本
|
||
special_texts = {} # 存星號開頭的特殊文本
|
||
namedesc_texts = {} # 存名稱和描述類的文本
|
||
|
||
# 掃描目錄裡所有txt檔案
|
||
for filename in os.listdir(path):
|
||
if filename.endswith(".txt"):
|
||
file_path = os.path.join(path, filename)
|
||
# 讀取檔案全部內容
|
||
with open(file_path, "r", encoding="utf-8") as f:
|
||
lines = f.readlines()
|
||
|
||
# 逐行分析內容
|
||
for i, line in enumerate(lines):
|
||
stripped = line.strip()
|
||
if should_ignore(stripped):
|
||
continue # 跳過不需要處理的行
|
||
|
||
# 生成唯一鍵值(檔案名+行號)
|
||
key = f"{filename}__{i}"
|
||
|
||
# 遇到名稱或描述類的文本(name:/desc:/menuDesc:)
|
||
if stripped.startswith(("name:", "desc:", "menuDesc:")):
|
||
# 把開頭的標記切掉,只留內容文字
|
||
idx = stripped.find(":")
|
||
namedesc_texts[key] = stripped[idx + 1:].strip()
|
||
# 遇到星號開頭的就是特殊文本
|
||
elif stripped.startswith("*"):
|
||
special_texts[key] = stripped
|
||
# 剩下的都當普通文本處理
|
||
else:
|
||
normal_texts[key] = stripped
|
||
|
||
return normal_texts, special_texts, namedesc_texts
|
||
|
||
def save_json(data, path, name):
|
||
"""把整理好的資料存成JSON檔案"""
|
||
# 先建立放翻譯檔的目錄(如果不存在就自動創建)
|
||
translate_dir = os.path.join(path, "translate")
|
||
os.makedirs(translate_dir, exist_ok=True)
|
||
|
||
# 組合完整檔案路徑
|
||
json_path = os.path.join(translate_dir, name)
|
||
# 寫入JSON格式(保持非ASCII字原樣顯示)
|
||
with open(json_path, "w", encoding="utf-8") as f:
|
||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||
|
||
def walk_and_process(root="."):
|
||
"""開始掃描整個資料夾結構,找出需要處理的目錄"""
|
||
# 走訪所有子目錄
|
||
for dirpath, dirnames, filenames in os.walk(root):
|
||
# 檢查目錄裡是否有txt檔案
|
||
txts_in_dir = [f for f in filenames if f.endswith(".txt")]
|
||
if not txts_in_dir:
|
||
continue # 跳過沒有txt檔的目錄
|
||
|
||
# 收集三類文本資料
|
||
normal, special, namedesc = collect_texts_from_txt(dirpath)
|
||
|
||
# 分別儲存不同類型的翻譯文件
|
||
if normal:
|
||
save_json(normal, dirpath, "translation.json")
|
||
print(f"✔ 已生成 translation.json 於 {dirpath}") # 提示
|
||
if special:
|
||
save_json(special, dirpath, "translation_special.json")
|
||
print(f"✔ 已生成 translation_special.json 於 {dirpath}")
|
||
if namedesc:
|
||
save_json(namedesc, dirpath, "translation_namedesc.json")
|
||
print(f"✔ 已生成 translation_namedesc.json 於 {dirpath}")
|
||
|
||
if __name__ == "__main__":
|
||
walk_and_process()
|
||
print("\n🏁 文本收集作業完成!") # 結尾提示 |