gpt4 book ai didi

python - 将 jupyter lab notebook 转换为脚本而不添加注释和单元格之间的新行

转载 作者:行者123 更新时间:2023-11-28 22:13:02 27 4
gpt4 key购买 nike

我如何将 jupyter lab notebook 转换为 *.py 而没有在转换时向脚本添加任何空行和注释(例如 # In[ 103]:)?我目前可以使用 jupyter nbconvert --to script 'test.ipynb' 进行转换,但这会在笔记本单元格之间添加空行和注释。

最佳答案

截至目前,jupyter 默认不提供此类功能。不过,您可以使用几行代码从 python 文件中手动删除空行和注释,例如

def process(filename):
"""Removes empty lines and lines that contain only whitespace, and
lines with comments"""

with open(filename) as in_file, open(filename, 'r+') as out_file:
for line in in_file:
if not line.strip().startswith("#") and not line.isspace():
out_file.writelines(line)

现在,只需在从 jupyter notebook 转换的 python 文件上调用此函数即可。

process('test.py')

此外,如果您希望使用单个实用程序函数将 jupyter notebook 转换为没有注释和空行的 python 文件,您可以在建议的以下函数中包含以上代码 here :

import nbformat
from nbconvert import PythonExporter

def convertNotebook(notebookPath, out_file):
with open(notebookPath) as fh:
nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)

exporter = PythonExporter()
source, meta = exporter.from_notebook_node(nb)

with open(out_file, 'w+') as out_file:
out_file.writelines(source)

# include above `process` code here with proper modification

关于python - 将 jupyter lab notebook 转换为脚本而不添加注释和单元格之间的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54338288/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com