簡體   English   中英

在 Jupyter 筆記本 Markdown 單元格 Python 中打印變量

[英]Print Variable In Jupyter Notebook Markdown Cell Python

我可以在 Markdown Cell Jupyter Notebook 中打印變量的值嗎?

試過的代碼:

value = 5.3

Markdown cell --> Value is {{ value }} 

我希望 Markdown 單元格應顯示變量的值

截屏

代碼截圖

@nilansh bansal 的回答非常適合 Jupyter Notebooks。 不幸的是,它不適用於 JupyterLab,因為該插件不再受支持(所有 nbextension 插件都是如此)。 由於 JupyterLab 越來越受歡迎,我想補充到目前為止的答案,因為我花了很長時間才找到解決方案。 這是因為到目前為止還沒有與 JupyterLab 兼容的插件。 通過結合這個這個SO 答案,我為自己找到了以下解決方案:

from IPython.display import Markdown as md
# Instead of setting the cell to Markdown, create Markdown from withnin a code cell!
# We can just use python variable replacement syntax to make the text dynamic
n = 10
md("The data consists of {} observations. Bla, Bla, ....".format(n))

或者,最后一行可以按照@Igor Fobia對於 Python > 3.6 的建議進行簡化:

md(f"The data consists of {n} observations. Bla, Bla, ....")

這會導致所需的輸出。 但是,它有一個巨大的缺點,即在導出 NB 時代碼單元仍然可見。 不過這可以解決:

  1. 在代碼單元格中添加一個標簽,即命名為“隱藏”
  2. 配置nbconvert以忽略標記的單元格,例如通過將此c.TagRemovePreprocessor.remove_input_tags = {"hide"}到您的~/.jupyter/jupyter_notebook_config.py配置文件

我寫了一篇詳細的博客文章,介紹了我如何實施此解決方案以在我的博客上發布 Notebook。 例如,您可以為jupyterlab-celltags安裝jupyterlab-celltags插件以簡化單元格標記。

因此,在瀏覽完所有鏈接后,我能夠通過參考 nbextension jupyter notebook 文檔來解決問題:https ://github.com/ipython-contrib/jupyter_contrib_nbextensions

采取的步驟:

  1. pip 安裝 jupyter_contrib_nbextensions
  2. jupyter contrib nbextension install --user
  3. jupyter nbextension 啟用 python-markdown/main

在上述命令啟動 jupyter notebook 並在 markdown 單元格中打印變量的值后,就像魅力一樣!

您只需要在降價單元格中使用{{ ac_score }} 即可

截屏

在此處輸入圖片說明

謝謝!

您可以覆蓋%%markdown IPython magic 以替換全局環境中的變量:

from IPython.display import Markdown
from IPython.core.magic import register_cell_magic


@register_cell_magic
def markdown(line, cell):
    return Markdown(cell.format(**globals()))

這具有在與 JupyterLab-LSP 一起使用時允許 Markdown linting 的優點。

如果使用 nbsphinx 開發文檔,您可以通過在單元格元數據中設置{"hide_input": true}來隱藏輸入(單元格的來源):

在此處輸入圖片說明 (注意Jupyter[Lab]LSP下划線,因為它們不在英語詞典中 - linting 有效!)

這導致像這樣的平滑文檔:

在此處輸入圖片說明

為了在 JupyterLab 中獲得更好的體驗,您始終可以通過單擊左側的藍色條來折疊輸入單元格(將鼠標懸停在單元格上時可見)。

{{URL+target+'/'+CODE+'.png?sidcode='+str(sidecode)}} # Shows URL Properly, BUT!...

![__img_01__]({{URL+target+'/'+CODE+'.png?sidcode='+str(sidecode)}}) # why? not working?
![__img_02__]({{URL}}{{target}}/{{CODE}}.png?sidcode={{sidecode}}) # Why not working either?

所以,我強烈推薦使用Ipython.display.Markdown
有誰知道上面的解決方案?

echo = f"""
## {NAME} ({CODE})
- target = '{target}'
- sidecode = '{sidecode}'
![__CHART_IMAGE__]({URL}{target}/{CODE}.png?sidcode={sidecode})
"""

Markdown(echo)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM