ipython notebook 隐藏代码_Jupyter-notebook隐藏代码

本文介绍了如何在Jupyter Notebook中隐藏代码,以便于创建报告或演示文稿。提供了两种方法:一种是通过添加按钮实现所有代码的隐藏和显示,另一种是在导出时直接隐藏代码。此外,还介绍了一种方法来隐藏特定cell的内容,以保持工作区整洁。
摘要由CSDN通过智能技术生成

Jupyter-notebook隐藏代码

有时候我们需要将jupyter-notebook导出为一个报告或者presentation的形式,不需要显示代码过程,只需要显示结果以及用markdown做的解释说明。有几种方式可以实现这个功能。我把下面的代码写成了函数集成在我的sciplot库里面了。

隐藏/显示代码按钮

在随便一个cell中加入以下代码并运行就可以得到一个按钮,点击它就可以实现隐藏和显示代码。在notebook中对所有代码起作用;但是对导出结果中只对hide所在cell起作用。

import ipywidgets as widgets

from IPython.display import display, HTML

javascript_functions = {False: "hide()", True: "show()"}

button_descriptions  = {False: "Show code", True: "Hide code"}

def toggle_code(state):

output_string = ""

output_args   = (javascript_functions[state],)

output        = output_string.format(*output_args)

display(HTML(output))

def button_action(value):

state = value.new

toggle_code(state)

value.owner.description = button_descriptions[state]

state = False

toggle_code(state)

button = widgets.ToggleButton(state, description = button_descriptions[state])

button.observe(button_action, "value")

display(button)

直接隐藏代码

同样在其中一个cell(建议放在最开始的一个cell中)中输入一下代码,这个在你自己编辑notebook时不起作用,对导出结果中所有代码起作用:导出html或者pdf中是没有代码的。同样把它定义为函数集成在sciplot里面方便调用。

from IPython.display import display

from IPython.display import HTML

import IPython.core.display as di

di.display_html('', raw=True)

CSS = """#notebook div.output_subarea {max-width:100%;}""" #changes output_subarea width to 100% (from 100% - 14ex)

HTML(''.format(CSS))

隐藏cell

上面的隐藏代码功能,针对所有的cell里面的代码显示或者隐藏。在我们编写notebook的过程中,有时候希望隐藏指定的cell(有可能因为有些cell里面的代码太长,我们不想看到它)。可以用一下代码实现,放在每一个cell里面,运行就会出现按钮能显示或者隐藏这个cell里面的内容。

this_cell = """$('div.cell.code_cell.rendered.selected')"""

next_cell = this_cell + '.next()'

toggle_text = '显示/隐藏'  # text shown on toggle link

target_cell = this_cell  # target cell to control with toggle

# bit of JS to permanently hide code in current cell (only when toggling next cell)

js_hide_current = ''

if for_next:

target_cell = next_cell

toggle_text += ' next cell'

js_hide_current = this_cell + '.find("div.input").hide();'

js_f_name = 'code_toggle_{}'.format(str(random.randint(1, 2**64)))

html = """

function {f_name}() {{

{cell_selector}.find('div.input').toggle();

}}

{js_hide_current}

{toggle_text}

""".format(

f_name=js_f_name,

cell_selector=target_cell,

js_hide_current=js_hide_current,

toggle_text=toggle_text

)

return HTML(html)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值