Javascript 如何从使用 nbviewer 可视化的 ipython notebook 中的单元格隐藏代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27934885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:57:20  来源:igfitidea点击:

How to hide code from cells in ipython notebook visualized with nbviewer?

javascriptipythonipython-notebook

提问by lucacerone

I have an ipython/jupyter notebook that I visualize using NBviewer.

我有一个使用 NBviewer 可视化的 ipython/jupyter 笔记本。

How can I hide all the code from the notebook rendered by NBviewer, so that only the output of code (e.g. plots and tables) and the markdown cells are shown?

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

回答by harshil

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

回答by Noah

This is now possible directly from nbconvert as of version 5.2.1: content can be filtered using the built-in template exporter exclude options. For example:

5.2.1版开始,现在可以直接从 nbconvert 进行此操作:可以使用内置模板导出器排除选项过滤内容。例如:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

will exclude the "input code" cells, ie the code itself. Similar optionsexist to exclude prompts, markdown cells, or outputs, or both inputs and outputs.

将排除“输入代码”单元格,即代码本身。存在类似的选项来排除提示、降价单元格或输出,或同时排除输入和输出。

(These options should work irrespective of output format.)

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

回答by user394430

I would use hide_input_allfrom nbextensions(https://github.com/ipython-contrib/IPython-notebook-extensions). Here's how:

我会用hide_input_allnbextensionshttps://github.com/ipython-contrib/IPython-notebook-extensions)。就是这样:

  1. Find out where your IPython directory is:

    from IPython.utils.path import get_ipython_dir
    print get_ipython_dir()
    
  2. Download nbextensionsand move it to the IPython directory.

  3. Edit your custom.jsfile somewhere in the IPython directory (mine was in profile_default/static/custom) to be similar to the custom.example.jsin the nbextensionsdirectory.

  4. Add this line to custom.js:

    IPython.load_extensions('usability/hide_input_all')
    
  1. 找出你的 IPython 目录在哪里:

    from IPython.utils.path import get_ipython_dir
    print get_ipython_dir()
    
  2. 下载nbextensions并将其移动到 IPython 目录。

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

  4. 将此行添加到custom.js

    IPython.load_extensions('usability/hide_input_all')
    

IPython Notebook will now have a button to toggle code cells, no matter the workbook.

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

回答by user394430

The newest IPython notebook version do not allow executing javascript in markdown cells anymore, so adding a new markdown cell with the following javascript code will not work anymore to hide your code cells (refer to this link)

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

Change ~/.ipython/profile_default/static/custom/custom.js as below:

更改 ~/.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>")
});

回答by Max Masnick

I wrote some code that accomplishes this, and adds a button to toggle visibility of code.

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

The following goes in a code cell at the top of a notebook:

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

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)

You can see an example of how this looks in NBviewer here.

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

Update:This will have some funny behavior with Markdown cells in Jupyter, but it works fine in the HTML export version of the notebook.

更新:Jupyter 中的 Markdown 单元格会有一些有趣的行为,但它在笔记本的 HTML 导出版本中运行良好。

回答by Erick Shepherd

This can be done using an IPython ToggleButtonwidget and a little bit of JavaScript. The following code should be placed into a code cell at the top of the document:

这可以使用 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)

This creates the following button to toggle showing/hiding the code for the Jupyter Notebook, defaulted to the "hide" state:

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

Hide code state

隐藏代码状态

When set to the "show" state, you can then see the code for the Jupyter Notebook:

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

Show code state

显示代码状态

As an aside, while much of this code should be placed at the beginning of the Notebook, the location of the toggle button is optional. Personally, I prefer to keep it at the bottom of the document. To do so, simply move the display(button)line to a separate code cell at the bottom of the page:

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

Relocated toggle button

Relocated toggle button

回答by Ken

There is a nice solution provided herethat works well for notebooks exported to HTML. The website even links back here to this SO post, but I don't see Chris's solution here! (Chris, where are you at?)

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

This is basically the same solution as the accepted answer from harshil, but it has the advantage of hiding the toggle code itself in the exported HTML. I also like that this approach avoids the need for the IPython HTML function.

这与来自harshil 的公认答案基本相同,但它的优点是将切换代码本身隐藏在导出的HTML 中。我也喜欢这种方法避免了对 IPython HTML 函数的需要。

To implement this solution, add the following code to a 'Raw NBConvert' cell at the top of your notebook:

要实现此解决方案,请将以下代码添加到笔记本顶部的“原始 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>

Then simply export the notebook to HTML. There will be a toggle button at the top of the notebook to show or hide the code.

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

Chris also provides an example here.

Chris 还在此处提供了一个示例。

I can verify that this works in Jupyter 5.0.0

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

Update: It is also convenient to show/hide the div.promptelements along with the div.inputelements. This removes the In [##]:and Out: [##]text and reduces the margins on the left.

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

回答by jaycode

For better display with printed document or a report, we need to remove the button as well, and the ability to show or hide certain code blocks. Here's what I use (simply copy-paste this to your first cell):

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

# 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>''')

Then in your next cells:

然后在你的下一个单元格中:

hide_me
print "this code will be hidden"

and

print "this code will be shown"

回答by Chase Wright

This will render an IPython notebook output. However, you will note be able to view the input code. You can copy a notebook, then add this code if needed to share with someone who does not need to view the code.

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

from IPython.display import HTML

HTML('''<script> $('div .input').hide()''')

回答by Valentas

Convert cell to Markdown and use HTML5 <details>tag as in the example by joyrexus:

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

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

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>