Jupyter-notebook隱藏代碼


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 = "<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(12**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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM