jupyter notebook批量翻译
时间: 2025-04-29 21:55:33 浏览: 32
### 批量翻译 Jupyter Notebook 文件
对于批量翻译 Jupyter Notebook 文件的需求,可以考虑采用自动化脚本结合翻译API的方式实现。由于Jupyter Notebook文件本质上是以JSON格式存储的文本和代码混合体,因此可以通过解析这些文件来提取其中的文字内容并进行翻译。
#### 使用Python脚本与Google Translate API
一种方法是编写一个Python脚本来遍历指定目录下的所有`.ipynb`文件,并利用像Google Translate这样的在线服务来进行文字部分的翻译工作。需要注意的是,这种方法只适用于翻译Markdown单元格以及注释中的自然语言描述;而不会影响到实际执行的编程语句[^1]。
```python
from googletrans import Translator
import json
import os
translator = Translator()
def translate_notebook(input_file, output_dir):
with open(input_file, 'r', encoding='utf-8') as f:
nb_data = json.load(f)
translated_cells = []
for cell in nb_data['cells']:
if cell['cell_type'] == 'markdown':
text_to_translate = '\n'.join(cell['source'])
translation_result = translator.translate(text_to_translate).text
new_cell = dict(cell)
new_cell['source'] = [translation_result]
translated_cells.append(new_cell)
elif cell['cell_type'] == 'code' and '# TRANSLATE ME' in ''.join(cell.get('metadata', {}).get('tags', [])):
comments = []
code_lines = []
for line in cell['source']:
stripped_line = line.strip()
if stripped_line.startswith('#'):
comment_translation = translator.translate(stripped_line[1:]).text
comments.append(f'# {comment_translation}\n')
else:
code_lines.append(line)
combined_source = comments + ['\n'] + code_lines
updated_cell = dict(cell)
updated_cell['source'] = combined_source
translated_cells.append(updated_cell)
else:
translated_cells.append(cell)
filename_without_extension = os.path.splitext(os.path.basename(input_file))[0]
output_filename = f"{filename_without_extension}_translated.ipynb"
full_output_path = os.path.join(output_dir, output_filename)
with open(full_output_path, 'w', encoding='utf-8') as out_f:
json.dump(dict(nb_data, cells=translated_cells), out_f, ensure_ascii=False, indent=2)
directory_containing_ipynbs = './notebooks'
output_directory_for_translated_files = './translated_notebooks'
if not os.path.exists(output_directory_for_translated_files):
os.makedirs(output_directory_for_translated_files)
for root, dirs, files in os.walk(directory_containing_ipynbs):
for name in files:
if name.endswith(".ipynb"):
input_filepath = os.path.join(root, name)
translate_notebook(input_filepath, output_directory_for_translated_files)
```
此段代码会读取给定路径下所有的 `.ipynb` 文件,并尝试将其 Markdown 单元格内的文本通过 Google Translate API 翻译成目标语言。此外,还可以标记特定代码块以便于它们内部的注释也能被处理。请注意,在使用任何第三方翻译服务之前,请仔细阅读其条款和服务协议[^2]。
阅读全文
相关推荐


















