Files
DRHPS/extract-strings.py
2025-03-04 18:40:19 +08:00

70 lines
3.0 KiB
Python

import os
import json
# 递归读取文件夹tmpgui中的所有JSON文件
def read_json_files(directory, textkeylist, textbox=False):
translation_dict = {} # 用来存储所有的m_text值
translation_set = set()
# 遍历目录中的所有文件和子目录
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".json"):
file_path = os.path.join(root, file)
# 读取每个json文件
with open(file_path, "r", encoding="utf-8") as f:
try:
data = json.load(f)
if textbox:
if data.get("Textboxes"):
arr = data["Textboxes"]["Array"]
for item in arr:
if item["Text"].get("Array"):
lines = item["Text"]["Array"]
else:
lines = [item["Text"]]
it = 0
for textvalue in lines:
if textvalue not in translation_set:
translation_dict[
file.replace(".json", "")
+ "-"
+ str(it)
] = textvalue
translation_set.add(textvalue)
it += 1
else:
for key in textkeylist:
textvalue = data.get(key) # 获取m_text属性的值
if textvalue and type(textvalue) == str:
if textvalue not in translation_set:
translation_dict[
file.replace(".json", "") + "-" + key
] = textvalue
translation_set.add(textvalue)
except json.JSONDecodeError:
print(f"文件 {file_path} 解析错误")
return translation_dict
# 将字典保存到transdict.json
def save_translation_dict(translation_dict, output_file):
with open(output_file, "w", encoding="utf-8") as f:
json.dump(translation_dict, f, ensure_ascii=False, indent=4)
# 主程序
def main():
save_translation_dict(read_json_files("text", ["m_text"]), "strings/mtext.json")
save_translation_dict(
read_json_files("text", ["SettingsElementName", "SettingsDescription"]),
"strings/settings.json",
)
save_translation_dict(read_json_files("text", [], True), "strings/dialogue.json")
if __name__ == "__main__":
main()