Jupyter-notebook隐藏代码(转载)

卞经业
2023-12-01

有时候我们需要将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 = "<script>$(\"div.input\").{}</script>"
    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('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)
CSS = """#notebook div.output_subarea {max-width:100%;}""" #changes output_subarea width to 100% (from 100% - 14ex)
HTML('<style>{}</style>'.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 = """
        <script>
            function {f_name}() {{
                {cell_selector}.find('div.input').toggle();
            }}

            {js_hide_current}
        </script>
        <a href="javascript:{f_name}()">{toggle_text}</a>
    """.format(
        f_name=js_f_name,
        cell_selector=target_cell,
        js_hide_current=js_hide_current,
        toggle_text=toggle_text
    )
    return HTML(html)

 

 类似资料: