使用 json.dump 书写时,在 iPython 笔记本中正确包含回车符 return

Include carriage return correctly in iPython notebooks when writing using json.dump

我正在尝试使用 Python 将 iPython 笔记本生成为 json 文件。我不确定如何在指定为 cell_type markdown 的单元格中写入回车符 returns 以归档。我已经按照 here 的建议尝试了双空格,我可以通过指定 <br /> 来让降价换行,但是如果我在降价中包含 header 规范,它会处理整个输入为 header。

例如:

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 打开它,我有以下输出:

Header行第二行,不是header...希望

但都是粗体字,所以整个输入被视为一行 header。

如何正确指定回车 returns,以便在我创建这些笔记本时,header 只显示一行?

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

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