如何隐藏使用nbviewer可视化的ipython笔记本中的单元格中的代码?

luc*_*one 126 javascript ipython ipython-notebook

我有一个ipython/jupyter笔记本,我用NBviewer可视化.

如何隐藏NBviewer呈现的笔记本中的所有代码,以便仅显示代码输出(例如绘图和表格)和降价单元格?

小智 206

from IPython.display import HTML

HTML('''<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
Run Code Online (Sandbox Code Playgroud)

  • 你怎么改变它所以它甚至没有显示按钮,它只是隐藏代码? (6认同)
  • 过去,这对于以 HTML 格式下载的笔记本来说效果很好,但现在我可以看到该按钮,但它没有执行任何操作。我正在运行 nb 服务器 6.1.4;Python 3.8.5;IPython 7.19.0。 (6认同)
  • 如果我把它放在代码单元格中,我会在iPython 3.1.0上为我工作.我用简单的HTML替换了`<form action ...> ... </ form>``这个IPython笔记本的原始代码默认是隐藏的,以便于阅读.要打开/关闭原始代码,请单击< a href ="javascript:code_toggle()">这里</a> .` (5认同)
  • 现在看来在新的IPython笔记本(3.10)上不起作用。 (3认同)
  • 谢谢,这也适用于"保存到HTML".建议将其放在笔记本顶部的自己的单元格中. (3认同)
  • 它仅适用于特定版本的 Ipython 吗?它曾经对我有用,但后来我更新了一些软件包(包括 Ipython),这不再起作用了。 (2认同)

Noa*_*oah 47

现在可以直接从版本5.2.1开始使用nbconvert :可以使用内置模板导出器排除选项过滤内容.例如:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb
Run Code Online (Sandbox Code Playgroud)

将排除"输入代码"单元格,即代码本身.存在类似的选项以排除提示,降价单元格或输出,或输入和输出.

(无论输出格式如何,这些选项都应该有效.)

  • 这是最好的答案 (2认同)

use*_*430 19

我会用hide_input_allnbextensions(https://github.com/ipython-contrib/IPython-notebook-extensions).这是如何做:

  1. 找出你的IPython目录的位置:

    from IPython.utils.path import get_ipython_dir
    print get_ipython_dir()
    
    Run Code Online (Sandbox Code Playgroud)
  2. 下载nbextensions并将其移至IPython目录.

  3. 编辑您custom.js在IPython的某个目录里的文件(我的是在profile_default /静态/自定义),以类似于 custom.example.jsnbextensions目录.

  4. 将此行添加到custom.js:

    IPython.load_extensions('usability/hide_input_all')
    
    Run Code Online (Sandbox Code Playgroud)

无论工作簿如何,IPython Notebook现在都有一个按钮来切换代码单元格.

  • 刚试过这个 - 它似乎有助于在编辑笔记本时隐藏代码单元,但是当将笔记本保存为html(即渲染到nbviewer)时,代码单元仍会出现. (6认同)

小智 15

最新的IPython笔记本版本不再允许在markdown单元格中执行javascript,因此使用以下javascript代码添加新的markdown单元格将无法再隐藏您的代码单元格(请参阅此链接)

更改〜/ .ipython/profile_default/static/custom/custom.js如下:

code_show=true;
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
}

$([IPython.events]).on("app_initialized.NotebookApp", function () {
  $("#view_menu").append("<li id=\"toggle_toolbar\" title=\"Show/Hide code cells\"><a href=\"javascript:code_toggle()\">Toggle Code Cells</a></li>")
});
Run Code Online (Sandbox Code Playgroud)


Eri*_*erd 13

这可以使用 IPythonToggleButton小部件和一点点 JavaScript 来完成。以下代码应放置在文档顶部的代码单元格中:

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):

    """
    Toggles the JavaScript show()/hide() function on the div.input element.
    """

    output_string = "<script>$(\"div.input\").{}</script>"
    output_args   = (javascript_functions[state],)
    output        = output_string.format(*output_args)

    display(HTML(output))


def button_action(value):

    """
    Calls the toggle_code function and updates the button description.
    """

    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)
Run Code Online (Sandbox Code Playgroud)

这将创建以下按钮来切换显示/隐藏 Jupyter Notebook 的代码,默认为“隐藏”状态:

隐藏代码状态

当设置为“显示”状态时,您可以看到 Jupyter Notebook 的代码:

显示代码状态

顺便说一句,虽然大部分代码应该放在 Notebook 的开头,但切换按钮的位置是可选的。就个人而言,我更喜欢将它放在文档的底部。为此,只需将该display(button)行移动到页面底部的单独代码单元格:

重新定位的切换按钮


小智 12

用于在编辑界面和导出的 html 中显示/隐藏 Jupyter Notebook 代码单元的脚本

只需将此代码放入第一个单元格并运行它:

%%HTML 
<script>
    function luc21893_refresh_cell(cell) {
        if( cell.luc21893 ) return;
        cell.luc21893 = true;
        console.debug('New code cell found...' );
        
        var div = document.createElement('DIV');            
        cell.parentNode.insertBefore( div, cell.nextSibling );
        div.style.textAlign = 'right';
        var a = document.createElement('A');
        div.appendChild(a);
        a.href='#'
        a.luc21893 = cell;
        a.setAttribute( 'onclick', "luc21893_toggle(this); return false;" );

        cell.style.visibility='hidden';
        cell.style.position='absolute';
        a.innerHTML = '[show code]';        
                
    }
    function luc21893_refresh() {                
        if( document.querySelector('.code_cell .input') == null ) {            
            // it apeears that I am in a exported html
            // hide this code
            var codeCells = document.querySelectorAll('.jp-InputArea')
            codeCells[0].style.visibility = 'hidden';
            codeCells[0].style.position = 'absolute';                        
            for( var i = 1; i < codeCells.length; i++ ) {
                luc21893_refresh_cell(codeCells[i].parentNode)
            }
            window.onload = luc21893_refresh;
        }                 
        else {
            // it apperas that I am in a jupyter editor
            var codeCells = document.querySelectorAll('.code_cell .input')
            for( var i = 0; i < codeCells.length; i++ ) {
                luc21893_refresh_cell(codeCells[i])
            }            
            window.setTimeout( luc21893_refresh, 1000 )
        }        
    }
    
    function luc21893_toggle(a) {
        if( a.luc21893.style.visibility=='hidden' ) {
            a.luc21893.style.visibility='visible';        
            a.luc21893.style.position='';
            a.innerHTML = '[hide code]';
        }
        else {
            a.luc21893.style.visibility='hidden';        
            a.luc21893.style.position='absolute';
            a.innerHTML = '[show code]';
        }
    }
    
    luc21893_refresh()
</script>
Run Code Online (Sandbox Code Playgroud)

编辑器中的示例

编辑器中的示例

导出的 HTML 示例

导出示例


Max*_*ick 10

我写了一些代码来实现这一点,并添加了一个按钮来切换代码的​​可见性.

以下内容位于笔记本顶部的代码单元格中:

from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)

# This line will hide code by default when the notebook is exported as HTML
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

# This line will add a button to toggle visibility of code blocks, for use with the HTML export version
di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看NBviewer的外观示例.

更新:这将对Jupyter中的Markdown单元格有一些有趣的行为,但它在笔记本的HTML导出版本中工作正常.

  • 这适用于代码单元格,但如果你有降价单元格,它会做一些奇怪的事情.它显示**markdown*为markdown***,然后显示相同的内容 - 但格式化 - 在下面. (3认同)

Val*_*tas 7

将单元格转换为 Markdown 并使用 HTML5<details>标签,如示例所示joyrexus

https://gist.github.com/joyrexus/16041f2426450e73f5df9391f7f7ae5f

## collapsible markdown?

<details><summary>CLICK ME</summary>
<p>

#### yes, even hidden code blocks!

```python
print("hello world!")
```

</p>
</details>
Run Code Online (Sandbox Code Playgroud)


jay*_*ode 6

为了更好地显示打印文档或报告,我们还需要删除按钮,以及显示或隐藏某些代码块的功能.这是我使用的(只需将其复制粘贴到您的第一个单元格):

# This is a cell to hide code snippets from displaying
# This must be at first cell!

from IPython.display import HTML

hide_me = ''
HTML('''<script>
code_show=true; 
function code_toggle() {
  if (code_show) {
    $('div.input').each(function(id) {
      el = $(this).find('.cm-variable:first');
      if (id == 0 || el.text() == 'hide_me') {
        $(this).hide();
      }
    });
    $('div.output_prompt').css('opacity', 0);
  } else {
    $('div.input').each(function(id) {
      $(this).show();
    });
    $('div.output_prompt').css('opacity', 1);
  }
  code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input style="opacity:0" type="submit" value="Click here to toggle on/off the raw code."></form>''')
Run Code Online (Sandbox Code Playgroud)

然后在你的下一个细胞中:

hide_me
print "this code will be hidden"
Run Code Online (Sandbox Code Playgroud)

print "this code will be shown"
Run Code Online (Sandbox Code Playgroud)


Ken*_*Ken 6

这里提供一个很好的解决方案 ,适用于导出到HTML的笔记本.该网站甚至链接到这个SO帖子,但我没有看到Chris的解决方案!(克里斯,你在哪里?)

这与harshil接受的答案基本上是相同的解决方案,但它具有将切换代码本身隐藏在导出的HTML中的优点.我也喜欢这种方法避免了对IPython HTML功能的需求.

要实现此解决方案,请将以下代码添加到笔记本顶部的"Raw NBConvert"单元格中:

<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()">
  <input type="submit" id="toggleButton" value="Show Code">
</form>
Run Code Online (Sandbox Code Playgroud)

然后只需将笔记本导出为HTML.笔记本顶部会有一个切换按钮来显示或隐藏代码.

克里斯还提供了一个例子在这里.

我可以验证这在Jupyter 5.0.0中有效

更新:显示/隐藏div.prompt元素以及div.input元素也很方便.这将删除In [##]:Out: [##]文本并减少左侧的边距.


Nav*_*mar 6

jupyter nbconvert yourNotebook.ipynb --no-input --no-prompt
Run Code Online (Sandbox Code Playgroud)

jupyter nbconvert yourNotebook.ipynb 这部分代码将采用jupyter笔记本的latex文件格式并将其转换为html

--no-input这就像我们在转换过程中所说的不添加任何输入的参数:这里单元格的输入是代码..所以我们隐藏它

--no-prompt在这里我们还要说,在转换过程中,不要在代码中显示任何提示,例如最终 HTML 文件中的错误或警告),以便该 html 将只有文本和以报告形式输出的代码!!..

希望能帮助到你 :)

  • 请添加一些解释,而不是简单地用命令回答。 (7认同)

小智 5

这将呈现 IPython 笔记本输出。但是,您将注意到能够查看输入代码。您可以复制笔记本,然后根据需要添加此代码以与不需要查看代码的人共享。

from IPython.display import HTML

HTML('''<script> $('div .input').hide()''')
Run Code Online (Sandbox Code Playgroud)