【问题标题】:Include carriage return correctly in iPython notebooks when writing using json.dump使用 json.dump 编写时,在 iPython 笔记本中正确包含回车
【发布时间】:2015-10-10 13:12:21
【问题描述】:

我正在尝试使用 Python 将 iPython 笔记本生成为 json 文件。我不确定如何在我指定为cell_type markdown 的单元格中写入回车符。正如here 所建议的那样,我尝试了双空格,并且我可以通过指定<br /> 来获取降价以创建新行,但是如果我在降价中包含标头规范,它会将整个输入视为标头。

例如:

import json

# Single markdown cell as a dictionary
cell = {
  "cell_type" : "markdown",
  "metadata" : {'collapsed': False, 'name': 'test'},
  "source" : ["## Header line",
    "<br />", 
    "Second line, not a header...hopefully"],
}

# Create ipython notebook dictionary
nbdict = { 'metadata': {}, \
    'nbformat': 4,
    'nbformat_minor': 0,
    'cells': [cell]
    }

with open('test.ipynb', 'w') as outfile:
    json.dump(nbdict, outfile)

如果我用ipython notebook test.ipynb 打开它,我会得到以下输出:

标题行第二行,不是标题...希望

但它都是粗体,所以整个输入被视为单行标题。

当我创建这些笔记本时,如何正确指定回车,以便仅使用一行标题?

【问题讨论】:

    标签: python json markdown ipython-notebook carriage-return


    【解决方案1】:

    Markdown 使用 newlines 来分隔行,而不是 HTML &lt;br/&gt; 标签。在源代码行中包含换行符;使用双换行符分隔段落元素(包括标题):

    cell = {
        "cell_type": "markdown",
        "metadata": {'collapsed': False, 'name': 'test'},
        "source": [
            "## Header line\n\n",
            "Second line, not a header...hopefully"
        ],
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多