[javascript] nbviewer로 시각화 된 ipython 노트북의 셀에서 코드를 숨기는 방법은 무엇입니까?

NBviewer를 사용하여 시각화하는 ipython / jupyter 노트북이 있습니다.

NBviewer가 렌더링 한 노트북에서 모든 코드를 숨겨서 코드 출력 (예 : 플롯 및 테이블)과 마크 다운 셀만 표시하려면 어떻게해야합니까?



답변

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


답변

이제 버전 5.2.1 부터 nbconvert에서 직접 사용할 수 있습니다. 기본 제공 템플릿 내보내기 제외 옵션을 사용하여 내용을 필터링 할 수 있습니다 . 예를 들면 다음과 같습니다.

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

“입력 코드”셀, 즉 코드 자체는 제외합니다. 프롬프트, 마크 다운 셀 또는 출력 또는 입력과 출력을 모두 제외하는 유사한 옵션있습니다 .

이러한 옵션은 출력 형식에 관계없이 작동해야합니다.


답변

내가 사용하는 것이 hide_input_all에서 nbextensions ( https://github.com/ipython-contrib/IPython-notebook-extensions )를. 방법은 다음과 같습니다.

  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.js 에서 nbextensions의 디렉토리.

  4. 이 행을 custom.js에 추가하십시오 .

    IPython.load_extensions('usability/hide_input_all')

이제 IPython Notebook에는 통합 문서에 관계없이 코드 셀을 전환 할 수있는 버튼이 있습니다.


답변

최신 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>")
});


답변

이 작업을 수행하는 코드를 작성하고 코드 가시성을 토글하는 버튼을 추가했습니다.

다음은 노트북 상단의 코드 셀에 들어갑니다.

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)

NBviewer에서 어떻게 보이는지에 대한 예를 여기서 볼 수 있습니다 .

업데이트 : Jupyter의 Markdown 셀에서 재미있는 동작을하지만 HTML 내보내기 버전의 노트북에서는 정상적으로 작동합니다.


답변

이것은 IPython ToggleButton위젯과 약간의 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)

그러면 Jupyter Notebook의 코드 표시 / 숨김을 토글하기 위해 다음과 같은 버튼이 생성되며 기본값은 “숨기기”상태입니다.

코드 상태 숨기기

“show”상태로 설정하면 Jupyter Notebook의 코드를 볼 수 있습니다.

코드 상태 표시

또한이 코드의 대부분은 노트북의 시작 부분에 배치해야하지만 토글 버튼의 ​​위치는 선택 사항입니다. 개인적으로 문서 하단에 보관하는 것을 선호합니다. 이렇게하려면 display(button)페이지 맨 아래에있는 별도의 코드 셀로 행을 이동 하십시오.

재배치 된 토글 버튼


답변

여기에는 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>

그런 다음 간단히 전자 필기장을 HTML로 내 보냅니다. 노트북 상단에는 코드를 표시하거나 숨길 수있는 토글 버튼이 있습니다.

Chris는 여기 에 예제를 제공합니다 .

Jupyter 5.0.0에서 작동하는지 확인할 수 있습니다.

업데이트 : div.prompt요소와 함께 요소 를 표시하거나 숨기는 것도 편리합니다 div.input. 그러면 In [##]:Out: [##]텍스트가 제거되고 왼쪽의 여백이 줄어 듭니다.