Jupyter笔记本标记单元Python中的打印变量

2024-05-23 20:57:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以在降价单元格Jupyter笔记本中打印变量的值吗?

尝试的代码:

value = 5.3

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

我希望标记单元格显示变量的值

屏幕截图

Screenshot for Code


Tags: 代码标记屏幕isvaluecell笔记本jupyter
3条回答
{{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)

@nilansh bansal的答案对Jupyter笔记本非常有用。不幸的是,它不适用于JupyterLab,因为该插件不再受支持(就像所有nbextension插件一样)。由于JupyterLab越来越受欢迎,我想补充到目前为止的答案,因为我花了相当长的时间来寻找解决方案。这是因为到目前为止还没有与JupyterLab兼容的插件。我通过组合thisthis找到了下面的解决方案,所以答案是:

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

或者,最后一行可以简化为Python的@Igor Fobia>;3.6所建议的那样:

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

这将产生所需的输出。然而,它有一个巨大的缺点,即导出NB时代码单元仍然可见。这可以通过以下方式解决:

  1. 在代码单元格中添加标记,即将其命名为“hide”
  2. 配置nbconvert忽略标记的单元格,例如,将此c.TagRemovePreprocessor.remove_input_tags = {"hide"}添加到~/.jupyter/jupyter_notebook_config.py配置文件中

我已经写了一篇详细的blog-post文章,介绍了如何在我的博客上实现这个用于发布笔记本的解决方案。例如,您可以安装JupyterLab的jupyterlab-celltags插件来简化细胞标记。

所以在浏览完所有链接之后,我可以通过引用nbextension jupyter笔记本文档来解决问题:https://github.com/ipython-contrib/jupyter_contrib_nbextensions

采取的步骤:

  1. pip安装jupyter_contrib_nbextensions
  2. jupyter contrib nbextension安装--用户
  3. jupyter nbextension启用python标记/main

在上面的命令启动了一个jupyter笔记本之后,在标记单元格中打印变量的值就变得非常有魅力了!

您只需在标记单元格中使用{{ac_score}}

屏幕截图

enter image description here

谢谢!

相关问题 更多 >