import json import pandas as pd from typing import Literal import os import shutil os.chdir(os.path.dirname(os.path.abspath(__file__))) class LanguageConvertor: def __init__(self, lang: Literal["en", "ja", "ko"]): self.lang = lang self.emotion = json.load(open("emotion.json", "r", encoding="utf-8"))[lang] self.data = pd.read_csv(f"characters_{self.lang}.csv") def get_name(self): names = self.data["名称"].tolist() return [name for i, name in enumerate(names) if name not in names[:i]] def replace_emotion(self): emotion = self.emotion for i, row in self.data.iterrows(): try: self.data.loc[i, "情绪"] = emotion[row["情绪"]] except KeyError: pass def generate_name_template(self, names: set[str]): res = "{\n" for i, name in enumerate(names): if i == len(names) - 1: res += f" \"{name}\": \"{name}\"\n" else: res += f" \"{name}\": \"{name}\",\n" with open(os.path.join("temp", f"translate_name_{self.lang}.json"), "w", encoding="utf-8") as f: f.write(res + "}") def replace_name(self): with open(os.path.join("temp", f"translate_name_{self.lang}.json"), "r", encoding="utf-8") as f: translate_name = json.load(f) for i, row in self.data.iterrows(): self.data.loc[i, "名称"] = translate_name[row["名称"]] def to_file(self): self.data.to_csv(f"characters_{self.lang}.csv", index=False) if __name__ == "__main__": # step = 1为生成翻译模板 # step = 2为生成翻译后的角色文件 # 请确保第一步已完成再进行第二步 step = 2 convertors = [LanguageConvertor(lang) for lang in ["en", "ja", "ko"]] os.makedirs("temp", exist_ok=True) for convertor in convertors: convertor.replace_emotion() print(convertor.data) if step == 1: convertor.generate_name_template(convertor.get_name()) if step == 2: for convertor in convertors: convertor.replace_name() convertor.to_file() # shutil.rmtree("temp")