我正在使用Jupyter Notebook。是否可以将所有输出保存为PDF文件?
例如,我有以下代码:
print('Hello World')
哪个输出:
Hello World
我只想将输出另存为PDF,而不是代码。我可以以某种方式自动执行此操作吗?
背景:我使用一个循环编写了一份分析报告,该循环输出一些图形,方程式和其他打印的语句。我现在正在寻找一种解决方案,以某种方式保存此输出结果。我看到这fpdf
似乎是可能的,但我无法安装它。因此,我想寻求另一种解决方案。
提前致谢!
你可以试试这个
步骤1
使用以下代码片段或Jupyter笔记本保存笔记本
from IPython.display import Javascript
from nbconvert import HTMLExporter
import codecs
import nbformat
def save_notebook():
display(
Javascript("IPython.notebook.save_notebook()"),
include=['application/javascript']
)
第2步
将笔记本转换为HTML(不包括代码单元格)
def output_HTML(read_file, output_file):
exporter = HTMLExporter()
# read_file is '.ipynb', output_file is '.html'
output_notebook = nbformat.read(read_file, as_version=4)
output, resources = exporter.from_notebook_node(output_notebook)
codecs.open(output_file, 'w', encoding='utf-8').write(output)
with open(output_file, 'r') as html_file:
content = html_file.read()
# Get rid off prompts and source code
content = content.replace("div.input_area {","div.input_area {\n\tdisplay: none;")
content = content.replace(".prompt {",".prompt {\n\tdisplay: none;")
f = open(output_file, 'w')
f.write(content)
f.close()
用法
保存笔记本
import time
save_notebook()
time.sleep(10)
current_file = 'Your Python Notebook.ipynb'
output_file = 'Output file Name.html'
调用output_HTML
函数
output_HTML(current_file, output_file)
接下来,您可以从浏览器将HTML输出转换为pdf(如果您使用的是Chrome)
它可能不是一个有效的解决方案,但也可以通过这种方式来完成。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句