| 181 | |
| 182 | # 翻译并保存结果,覆盖原文件 |
| 183 | def translate_and_save(lines, chinese_texts, lang, shrink, file_path): |
| 184 | translations = {} # 每种语言有自己的翻译结果 |
| 185 | threads = [] |
| 186 | chunk_size = len(chinese_texts) // 50 or 1 # 加大数量 |
| 187 | for i in range(0, len(chinese_texts), chunk_size): |
| 188 | chunk = chinese_texts[i:i + chunk_size] |
| 189 | thread = threading.Thread(target=translate_worker, args=(chunk, translations, lang)) |
| 190 | threads.append(thread) |
| 191 | thread.start() |
| 192 | # 等待所有线程完成 |
| 193 | for thread in threads: |
| 194 | thread.join() |
| 195 | # 从后往前替换中文文本 |
| 196 | new_lines = lines[:] |
| 197 | for line_number, chinese_text, translated_text in reversed( |
| 198 | [(ln, ct, translations.get((ln, ct), None)) for ln, ct in chinese_texts if (ln, ct) in translations]): |
| 199 | new_lines[line_number] = new_lines[line_number].replace( |
| 200 | chinese_text, translated_text, 1) |
| 201 | if shrink: # 允许创建多级目录,将每个语言作为单独的readme.md文件 |
| 202 | output_dir = os.path.dirname(file_path) |
| 203 | dir_with_lang = os.path.join(output_dir, lang) |
| 204 | if not os.path.exists(dir_with_lang): |
| 205 | os.makedirs(dir_with_lang) |
| 206 | output_path = os.path.join(dir_with_lang, 'README.md') |
| 207 | with open(output_path, 'w', encoding='utf-8') as f_out: |
| 208 | f_out.writelines(new_lines) |
| 209 | print(f"翻译完成,收缩到 [{lang}]目录,写入内容到'{output_path}'") |
| 210 | else: |
| 211 | with open(file_path, 'w', encoding='utf-8') as f_out: |
| 212 | f_out.writelines(new_lines) |
| 213 | print(f"翻译完成,已将结果覆盖保存到 '{file_path}'") |