def get_all_files_in_directory(directory, ext=''): import os import re custom_sort_key_re = re.compile('([0-9]+)') def custom_sort_key(s): # 将字符串中的数字部分转换为整数,然后进行排序 return [int(x) if x.isdigit() else x for x in custom_sort_key_re.split(s)] all_files = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith(ext): file_path = os.path.join(root, file) all_files.append(file_path) return sorted(all_files, key=custom_sort_key) def clearT(): import unicodedata from opencc import OpenCC def full2half(input_str): return ''.join([unicodedata.normalize('NFKC', char) for char in input_str]) cc = OpenCC('t2s') # 't2s'表示繁体转简体 def _clearT(s): s = cc.convert(full2half(s)) return s.strip().replace('\n', '\\n') return _clearT clearT = clearT() def simpleSplit(_s: str, _sp, _st = 0, _shift=True): _idx = _s.index(_sp, _st) if _shift: return _s[:_idx], _s[_idx+len(_sp):] else: return _s[:_idx], _s[_idx:] # ================= a = get_all_files_in_directory(r'E:\tmp\恋狱~月狂病\text', ext='') b = r'E:\tmp\恋狱~月狂病\c' # ================= sc = {} _n = { "@秋五": "秋五", "@有岛": "有岛", "@???": "?", "@和菜": "和菜", "@庆一郎": "庆一郎", "@由良": "由良", "@老爹": "老爹", "@凛": "凛", "@初音": "初音", "@乙羽": "乙羽", "@七七": "七七", "@小雪": "小雪", "@冬史": "冬史", "@良子": "良子", "@男": "男", "@大妈": "大妈", "@小孩": "小孩", "@板长": "板长", "@修女": "修女", "@警察": "警察", "@围观者": "围观者", "@八木沼": "八木沼", "@雨雀": "雨雀", "@厨师长": "厨师长", "@领班": "领班", "@楼子": "楼子", "@赤尾": "赤尾", "@信徒": "信徒", "@时子": "时子", "@信者": "信者", "@芹": "芹", "@樱": "樱", "@警察官": "警察官", "@刑事": "刑事", "@护士": "护士", "@护士小姐": "护士小姐", "@薇奥莉塔": "薇奥莉塔", "@阿弗列德": "阿弗列德", "@乔治": "乔治", "@男爵": "男爵", "@侍女": "侍女", "@少女": "少女" } for path in a: name = path[path.rindex('\\') + 1:] name = name[:1] if name not in sc: sc[name] = [] print(name) # ================= with open(path, 'r', encoding='utf-8') as f: data = list(filter(lambda x: x, (x.rstrip() for x in f.readlines()))) # ================= n = '旁白' w_i = -1 prefix = '' while w_i < len(data) - 1: w_i += 1 line: str = data[w_i] # ================= if '|' not in line: continue tmp, line = simpleSplit(line, '|') if tmp != prefix: prefix = tmp continue if line.startswith('@'): n, line = simpleSplit(line, '@', 1) if n in _n: n = _n[n] else: _n[n] = clearT(n.strip('@')).replace('/', '&') print(line) else: n = '旁白' d = clearT(line) if d: sc[name].append(n + ':' + d) # ================= for k, v in sc.items(): if v: with open(b + f'\\{k}.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(v)) # ================= import json tmp = json.dumps(_n, ensure_ascii=False, indent=4)