import pandas as pd import os import re # 需要处理的原始 csv 名字(不带后缀) csv_list = [ 'dialogs', 'factions', 'game_menus', 'game_strings', 'info_pages', 'item_kinds', 'item_modifiers', 'parties', 'party_templates', 'quests', 'quick_strings', 'skills', 'skins', 'troops', 'ui' ] def space_for_game(text: str) -> str: text = text.replace(' ', '') tokens = re.findall(r'[A-Za-z0-9{}_%$@]+|.', text) return ' '.join(tokens) def process_csv(path: str): """ 从 ./path.csv 中提取文本,按行分割: left|right -> id = left, text = right 并把 text 列保存到 extract/path.csv,供翻译使用。 """ csv_path = f'./{path}.csv' rows = [] # 新建 extract 文件夹 os.makedirs('extract', exist_ok=True) # 读取原始 csv,每行只按第一个 | 分割 with open(csv_path, 'r', encoding='utf-8', errors='ignore') as f: for line in f: line = line.rstrip('\n') left, right = (line.split('|', 1) + [''])[:2] rows.append([left, right]) df = pd.DataFrame(rows, columns=['id', 'text']) # 如果你想去掉 text 中所有空格,可以打开下面这一行 # df['text'] = df['text'].str.replace(' ', '') out_path = f'extract/{os.path.basename(path)}.csv' df['text'].to_csv(out_path, index=False, header=False, encoding='utf-8') print(f'[提取完成] {csv_path} -> {out_path}') def combine_csv(): # 新建 combine 文件夹 os.makedirs('combine', exist_ok=True) for name in csv_list: original_path = f'./{name}.csv' extract_path = f'./extract/{name}.csv' out_path = f'./combine/{name}.csv' if not os.path.exists(original_path): print(f'[跳过] 找不到原始文件:{original_path}') continue if not os.path.exists(extract_path): print(f'[跳过] 找不到翻译文件:{extract_path}') continue # 1) 读取原始文件,拿到所有 id(左边部分) ids = [] with open(original_path, 'r', encoding='utf-8', errors='ignore') as f: for line in f: line = line.rstrip('\n') left, _ = (line.split('|', 1) + [''])[:2] ids.append(left) # 2) 读取翻译后的 text(每行一条) # 这里假设你只改了内容,没有增加/减少行 df_trans = pd.read_csv(extract_path, header=None, encoding='utf-8') # 防止多列情况,这里取最后一列 translated_texts = df_trans.iloc[:, -1].astype(str).tolist() # 3) 对齐长度(防止不小心少翻 / 多翻了几行) n_ids = len(ids) n_txt = len(translated_texts) n = min(n_ids, n_txt) if n_ids != n_txt: print( f'[警告] {name}: 原始行数 = {n_ids}, 翻译行数 = {n_txt},' f'将只使用前 {n} 行进行合并' ) # 4) 写出新的 csv:id|translated_text with open(out_path, 'w', encoding='utf-8') as f_out: for i in range(n): text_spaced = space_for_game(translated_texts[i]) new_line = f"{ids[i]}|{text_spaced}" f_out.write(new_line + '\n') print(f'[合并完成] {original_path} + {extract_path} -> {out_path}') def main(): while True: print('请选择想要执行的操作:') print('A:从原始 csv 提取 text 到 extract/') print('B:用翻译后的 text 替换并生成 combine/ 下的新 csv') print('Q:退出程序') choice = input('输入 A 或 B 或 Q:').strip().upper() if choice == 'A': for csv_name in csv_list: process_csv(csv_name) elif choice == 'B': combine_csv() elif choice == 'Q': break else: print('输入错误,请重新运行并输入 A 或 B 或 Q') if __name__ == '__main__': main()