腳本變更

This commit is contained in:
wasneet 2025-05-01 10:35:32 +08:00
parent b11fc9bcb8
commit 1d4434bcf0
2 changed files with 178 additions and 100 deletions

View File

@ -1,118 +1,157 @@
import os
import json
import hashlib
# 获取当前文件所在的目录
root_dir = os.path.dirname(os.path.abspath(__file__))
# 获取翻译文件所在的目录
translate_dir = os.path.join(root_dir, 'translate')
# 加载翻译文件
def load_translation(filename):
with open(os.path.join(translate_dir, filename), 'r', encoding='utf-8') as f:
path = os.path.join(translate_dir, filename)
if not os.path.exists(path):
return {}
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
# 将文本转换为id
def text_to_id(text):
return hashlib.md5(text.encode('utf-8')).hexdigest()
# 判断是否需要将/n替换为\n
def need_real_newline(file_path):
relative_path = os.path.relpath(file_path, root_dir)
return (relative_path.startswith('Main') or
(relative_path.startswith('Rooms') and not relative_path.startswith('Rooms/Intro')) or
relative_path.startswith('Shops'))
# 加载翻译数据
print("📥 載入翻譯資料庫...")
star_texts = load_translation('StarText.json')
desc_texts = load_translation('DescText.json')
other_texts = load_translation('OtherText.json')
block_texts = load_translation('BlockText.json')
choices_texts = load_translation('Choices.json')
print("✅ 翻譯資料已成功載入。\n")
import hashlib
def text_to_id(text):
return hashlib.md5(text.encode('utf-8')).hexdigest()
def is_separator(line):
return line.startswith('@') or line.startswith('>') or line.startswith('.') or line.startswith('END')
def need_real_newline(file_path):
rel_path = os.path.relpath(file_path, root_dir).replace('\\', '/')
return rel_path == 'Main.txt' or \
(rel_path.startswith('Rooms/') and os.path.basename(file_path) != 'Intro.txt') or \
rel_path.startswith('Shops/')
SPECIAL_PREFIXES = [
"name:", "desc:", "menuDesc:", "shopDesc:",
"lwEquip:", "equipEffect:", "descriptionDW:"
]
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, root_dir)
mode = 'block' if (
rel_path == 'Main.txt' or
rel_path.startswith(('Rooms/', 'Rooms\\', 'Shops/', 'Shops\\'))
and not (rel_path.startswith('Rooms') and os.path.basename(file) == 'Intro.txt')
) else 'normal'
# 遍历根目录下的所有文件
for foldername, subfolders, filenames in os.walk(root_dir):
# 如果是翻译文件夹,则跳过
if 'translate' in foldername:
continue
print(f"📁 掃描資料夾:{foldername}")
for filename in filenames:
# 如果是txt文件则进行处理
if filename.endswith('.txt'):
file_path = os.path.join(foldername, filename)
relative_path = os.path.relpath(file_path, root_dir)
# 判断文件类型
mode = 'block' if relative_path.startswith(('Main', 'Rooms', 'Shops')) else 'normal'
print(f"🔄 處理檔案:{relative_path}(模式:{mode}")
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
new_lines = []
real_newline = need_real_newline(file_path)
# 如果是block模式
if mode == 'block':
block = []
for line in lines:
line = line.rstrip('\n')
if is_separator(line):
# 如果行以@、>、.、END开头则处理
if line.startswith('@') or line.startswith('>') or line.startswith('.') or line.startswith('END'):
# 如果block不为空则处理
if block:
text = '\n'.join(block)
id_ = text_to_id(text)
restored = block_texts.get(id_, text)
if real_newline:
restored = restored.replace('/n', '\n')
new_lines.extend(restored.split('\n'))
original_text = '\n'.join(block)
id = text_to_id(original_text)
translated = block_texts.get(id, original_text)
# 如果需要将/n替换为\n则替换
if need_real_newline(file_path):
translated = translated.replace('/n', '\n')
else:
translated = translated.replace('\n', '/n')
new_lines.append(translated)
block = []
# 如果行以>prompt:开头,则处理
if line.startswith('>prompt:'):
text = line[len('>prompt:'):]
id = text_to_id(text.replace(':', '/n'))
translated = choices_texts.get(id, text.replace(':', '/n'))
translated_line = '>prompt:' + translated.replace('/n', ':')
new_lines.append(translated_line)
else:
new_lines.append(line)
else:
block.append(line)
# 如果block不为空则处理
if block:
text = '\n'.join(block)
id_ = text_to_id(text)
restored = block_texts.get(id_, text)
if real_newline:
restored = restored.replace('/n', '\n')
new_lines.extend(restored.split('\n'))
original_text = '\n'.join(block)
id = text_to_id(original_text)
translated = block_texts.get(id, original_text)
# 如果需要将/n替换为\n则替换
if need_real_newline(file_path):
translated = translated.replace('/n', '\n')
else:
translated = translated.replace('\n', '/n')
new_lines.append(translated)
# 如果是normal模式
else:
i = 0
while i < len(lines):
line = lines[i].rstrip('\n')
if is_separator(line):
# 如果行以@、>、.、END开头则处理
if line.startswith('@') or line.startswith('>') or line.startswith('.') or line.startswith('END'):
# 如果行以>prompt:开头,则处理
if line.startswith('>prompt:'):
text = line[len('>prompt:'):]
id = text_to_id(text.replace(':', '/n'))
translated = choices_texts.get(id, text.replace(':', '/n'))
translated_line = '>prompt:' + translated.replace('/n', ':')
new_lines.append(translated_line)
else:
new_lines.append(line)
i += 1
continue
# 如果行以*开头,则处理
if line.startswith('*'):
id_ = text_to_id(line)
restored = star_texts.get(id_, line)
restored = restored.replace('/n', '\n' if real_newline else '/n')
new_lines.append(restored)
elif any(line.startswith(prefix) for prefix in SPECIAL_PREFIXES):
if ':' in line:
prefix_part, content_part = line.split(':', 1)
original_content = content_part.strip()
id_ = text_to_id(original_content)
restored_content = desc_texts.get(id_, original_content)
if real_newline:
restored_content = restored_content.replace('/n', '\n')
new_lines.append(f"{prefix_part}: {restored_content}")
id = text_to_id(line)
translated = star_texts.get(id, line)
new_lines.append(translated)
# 如果行以name:、desc:、lwEquip:、shopDesc:、equipEffect:、descriptionDW:、menuDesc:开头,则处理
elif (line.startswith('name:') or line.startswith('desc:') or line.startswith('lwEquip:')
or line.startswith('shopDesc:') or line.startswith('equipEffect:')
or line.startswith('descriptionDW:') or line.startswith('menuDesc:')):
prefix, content = line.split(':', 1)
content = content.strip()
id = text_to_id(content)
translated = desc_texts.get(id, content)
new_lines.append(f"{prefix}: {translated}")
# 如果行以party:开头,则处理
elif line.startswith('party:'):
new_lines.append('party:')
new_lines.append(line)
i += 1
while i < len(lines):
subline = lines[i].rstrip('\n')
if subline.startswith('|'):
id_ = text_to_id(subline)
restored = desc_texts.get(id_, subline)
restored = restored.replace('/n', '\n' if real_newline else '/n')
new_lines.append(restored)
id = text_to_id(subline)
translated = desc_texts.get(id, subline)
new_lines.append(translated)
i += 1
else:
break
continue
else:
id_ = text_to_id(line)
restored = other_texts.get(id_, line)
restored = restored.replace('/n', '\n' if real_newline else '/n')
new_lines.append(restored)
id = text_to_id(line)
translated = other_texts.get(id, line)
new_lines.append(translated)
i += 1
# 将处理后的内容写入文件
with open(file_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(new_lines))
f.write('\n'.join(new_lines) + '\n')
print(f"✅ 翻譯完成:{file_path}\n")
print("🎉 所有檔案已完成翻譯注入。")
# 註釋:
# 導入之前先把Choices中的\n替換成/nDescTexts中的\n替換成\\nStarText中的\n替換成\\n、\\t替換成\t。

View File

@ -2,71 +2,97 @@ import os
import json
import hashlib
# 获取当前文件所在的目录
root_dir = os.path.dirname(os.path.abspath(__file__))
# 定义翻译文件的目录
translate_dir = os.path.join(root_dir, 'translate')
os.makedirs(translate_dir, exist_ok=True)
# 生成唯一ID
def generate_id(text):
hash_object = hashlib.md5(text.encode('utf-8'))
return hash_object.hexdigest()
return hashlib.md5(text.encode('utf-8')).hexdigest()
text_to_id = {}
def save_json_with_ids(filename, text_list_or_dict):
# 保存JSON文件
def save_json_with_ids(filename, text_list):
# 创建翻译文件目录
os.makedirs(translate_dir, exist_ok=True)
# 定义输出文件路径
output_path = os.path.join(translate_dir, filename)
# 定义输出内容
output = {}
if isinstance(text_list_or_dict, list):
for text in text_list_or_dict:
id_ = text_to_id.setdefault(text, generate_id(text))
output[id_] = text.replace('\n', '/n')
else:
for key, text in text_list_or_dict.items():
id_ = text_to_id.setdefault(text, generate_id(text))
output[id_] = text.replace('\n', '/n')
with open(os.path.join(translate_dir, filename), 'w', encoding='utf-8') as f:
for text in text_list:
output[generate_id(text)] = text
# 将内容写入文件
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(output, f, ensure_ascii=False, indent=2)
# 打印保存信息
print(f"✅ 已儲存:{filename}(共 {len(text_list)} 筆)")
# 判断是否为分隔符
def is_separator(line):
return line.startswith('@') or line.startswith('>') or line.startswith('.') or line.startswith('END')
# 定义不同类型的文本列表
star_texts = []
desc_texts = []
other_texts = []
block_texts = []
choices_texts = []
# 处理文件
def process_file(path, mode):
# 打印处理文件信息
print(f"📄 正在處理檔案:{path}")
# 读取文件内容
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 根据模式处理文件
if mode == 'block':
block = []
for line in lines:
line = line.rstrip('\n')
# 判断是否为分隔符
if is_separator(line):
# 如果有内容则添加到block_texts中
if block:
block_texts.append('\n'.join(block))
block = []
# 如果是>prompt:开头则添加到choices_texts中
if line.startswith('>prompt:'):
text = line[len('>prompt:'):].replace(':', '/n')
if text not in choices_texts:
choices_texts.append(text)
else:
# 否则添加到block中
block.append(line)
# 如果有内容则添加到block_texts中
if block:
block_texts.append('\n'.join(block))
else:
i = 0
while i < len(lines):
line = lines[i].rstrip('\n')
# 判断是否为分隔符
if is_separator(line):
# 如果是>prompt:开头则添加到choices_texts中
if line.startswith('>prompt:'):
text = line[len('>prompt:'):].replace(':', '/n')
if text not in choices_texts:
choices_texts.append(text)
i += 1
continue
# 如果是*开头则添加到star_texts中
if line.startswith('*'):
if line not in star_texts:
star_texts.append(line)
# 如果是name:、desc:、lwEquip:、shopDesc:、equipEffect:、descriptionDW:、menuDesc:开头则添加到desc_texts中
elif (line.startswith('name:') or line.startswith('desc:') or line.startswith('lwEquip:')
or line.startswith('shopDesc:') or line.startswith('equipEffect:')
or line.startswith('descriptionDW:') or line.startswith('menuDesc:')):
content = line.split(':', 1)[1].strip()
if content not in desc_texts:
desc_texts.append(content)
# 如果是party:开头则添加到desc_texts中
elif line.startswith('party:'):
i += 1
while i < len(lines):
@ -78,25 +104,38 @@ def process_file(path, mode):
else:
break
continue
# 否则添加到other_texts中
else:
if line not in other_texts:
other_texts.append(line)
i += 1
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, root_dir)
if rel_path == 'Main.txt' or rel_path.startswith('Rooms\\') or rel_path.startswith('Rooms/') or rel_path.startswith('Shops\\') or rel_path.startswith('Shops/'):
if rel_path.startswith('Rooms') and os.path.basename(file) == 'Intro.txt':
process_file(file_path, mode='normal')
else:
process_file(file_path, mode='block')
else:
process_file(file_path, mode='normal')
# 开始扫描文件夹
print("🔍 開始掃描資料夾...\n")
# 遍历文件夹
for foldername, subfolders, filenames in os.walk(root_dir):
# 如果是翻译文件夹,则跳过
if 'translate' in foldername:
continue
# 打印扫描文件夹信息
print(f"📁 掃描資料夾:{foldername}")
# 遍历文件
for filename in filenames:
# 如果是txt文件则处理
if filename.endswith('.txt'):
file_path = os.path.join(foldername, filename)
relative_path = os.path.relpath(file_path, root_dir)
# 根据文件路径判断模式
mode = 'block' if relative_path.startswith(('Main', 'Rooms', 'Shops')) else 'normal'
process_file(file_path, mode)
# 保存翻译JSON文件
print("\n💾 儲存翻譯 JSON 檔案中...")
save_json_with_ids('StarText.json', star_texts)
save_json_with_ids('DescText.json', desc_texts)
save_json_with_ids('OtherText.json', other_texts)
save_json_with_ids('BlockText.json', block_texts)
save_json_with_ids('Choices.json', choices_texts)
print("\n✨ 作業完成。")
# 註釋:
# 導入之後先把Choices中的/n替換成\nDescTexts中的\\n替換成\nStarText中的\\n替換成\n、\t替換成\\t。