本文整理汇总了Python中nbformat.NotebookNode方法的典型用法代码示例。如果您正苦于以下问题:Python nbformat.NotebookNode方法的具体用法?Python nbformat.NotebookNode怎么用?Python nbformat.NotebookNode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nbformat
的用法示例。
在下文中一共展示了nbformat.NotebookNode方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_html_from_notebook
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def generate_html_from_notebook(self, nb: NotebookNode) -> Text:
"""Converts a provided NotebookNode to HTML.
Args:
nb: NotebookNode that should be converted to HTML.
Returns:
HTML from converted NotebookNode as a string.
"""
# HTML generator and exporter object
html_exporter = HTMLExporter()
template_file = "templates/{}.tpl".format(self.template_type.value)
html_exporter.template_file = str(Path.cwd() / template_file)
# Output generator
self.ep.preprocess(nb, {"metadata": {"path": Path.cwd()}}, self.km)
# Export all html and outputs
body, _ = html_exporter.from_notebook_node(nb, resources={})
return body
示例2: read
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def read(self, notebook, context=None):
assert isinstance(notebook, nbformat.NotebookNode)
self.resources = {} # Dictionary {filename: data}.
context = context or {}
# Get the unique key for image names: basename of the output file, if it exists.
self._unique_key = op.basename(context.get('output', None) or '')
self._unique_key = self._unique_key or op.basename(context.get('path', None) or '')
self._unique_key = op.splitext(self._unique_key)[0] or None
# Create the output tree.
self.tree = ASTNode('root')
# Language of the notebook.
m = notebook.metadata
# NOTE: if no language is available in the metadata, use Python
# by default.
self.language = m.get('language_info', {}).get('name', 'python')
# NOTE: for performance reasons, we parse the Markdown of all cells at once
# to reduce the overhead of calling pandoc.
self._markdown_tree = []
self._read_all_markdown(notebook.cells)
for cell_index, cell in enumerate(notebook.cells):
getattr(self, 'read_{}'.format(cell.cell_type))(cell, cell_index)
return self.tree
示例3: combine_notebooks
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def combine_notebooks(notebook_files: Sequence[Path]) -> NotebookNode:
combined_nb = new_notebook()
count = 0
for filename in notebook_files:
count += 1
log.debug('Adding notebook: %s', filename)
nbname = filename.stem
nb = nbformat.read(str(filename), as_version=4)
try:
combined_nb.cells.extend(add_sec_label(nb.cells[0], nbname))
except NoHeader:
raise NoHeader("Failed to find header in " + filename)
combined_nb.cells.extend(nb.cells[1:])
if not combined_nb.metadata:
combined_nb.metadata = nb.metadata.copy()
log.info('Combined %d files' % count)
return combined_nb
示例4: from_notebook_node
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def from_notebook_node(self, nb, resources=None, **kw):
"""
Convert a notebook from a notebook node instance.
Parameters
----------
nb : :class:`~nbformat.NotebookNode`
Notebook node (dict-like with attr-access)
resources : dict
Additional resources that can be accessed read/write by
preprocessors and filters.
`**kw`
Ignored
"""
nb_copy = copy.deepcopy(nb)
resources = self._init_resources(resources)
if 'language' in nb['metadata']:
resources['language'] = nb['metadata']['language'].lower()
# Preprocess
nb_copy, resources = self._preprocess(nb_copy, resources)
return nb_copy, resources
示例5: generate_notebook_from_arguments
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def generate_notebook_from_arguments(
self,
arguments: dict,
source: Text,
visualization_type: Text
) -> NotebookNode:
"""Generates a NotebookNode from provided arguments.
Args:
arguments: JSON object containing provided arguments.
source: Path or path pattern to be used as data reference for
visualization.
visualization_type: Name of visualization to be generated.
Returns:
NotebookNode that contains all parameters from a post request.
"""
nb = new_notebook()
nb.cells.append(exporter.create_cell_from_args(arguments))
nb.cells.append(new_code_cell('source = "{}"'.format(source)))
if visualization_type == "custom":
code = arguments.get("code", [])
nb.cells.append(exporter.create_cell_from_custom_code(code))
else:
visualization_file = str(Path.cwd() / "types/{}.py".format(visualization_type))
nb.cells.append(exporter.create_cell_from_file(visualization_file))
return nb
示例6: create_cell_from_args
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def create_cell_from_args(variables: dict) -> NotebookNode:
"""Creates NotebookNode object containing dict of provided variables.
Args:
variables: Arguments that need to be injected into a NotebookNode.
Returns:
NotebookNode with provided arguments as variables.
"""
return new_code_cell("variables = {}".format(repr(variables)))
示例7: create_cell_from_file
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def create_cell_from_file(filepath: Text) -> NotebookNode:
"""Creates a NotebookNode object with provided file as code in node.
Args:
filepath: Path to file that should be used.
Returns:
NotebookNode with specified file as code within node.
"""
with open(filepath, 'r') as f:
code = f.read()
return new_code_cell(code)
示例8: create_cell_from_custom_code
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def create_cell_from_custom_code(code: list) -> NotebookNode:
"""Creates a NotebookNode object with provided list as code in node.
Args:
code: list representing lines of code to be run.
Returns:
NotebookNode with specified file as code within node.
"""
cell = new_code_cell("\n".join(code))
cell.get("metadata")["hide_logging"] = False
return cell
示例9: new_latex_cell
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def new_latex_cell(source=''):
return NotebookNode(
cell_type='raw',
metadata=NotebookNode(raw_mimetype='text/latex'),
source=source,
)
示例10: add_sec_label
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def add_sec_label(cell: NotebookNode, nbname) -> Sequence[NotebookNode]:
"""Adds a Latex \\label{} under the chapter heading.
This takes the first cell of a notebook, and expects it to be a Markdown
cell starting with a level 1 heading. It inserts a label with the notebook
name just underneath this heading.
"""
assert cell.cell_type == 'markdown', cell.cell_type
lines = cell.source.splitlines()
if lines[0].startswith('# '):
header_lines = 1
elif len(lines) > 1 and lines[1].startswith('==='):
header_lines = 2
else:
raise NoHeader
header = '\n'.join(lines[:header_lines])
intro_remainder = '\n'.join(lines[header_lines:]).strip()
res = [
new_markdown_cell(header),
new_latex_cell('\label{sec:%s}' % nbname)
]
res[0].metadata = cell.metadata
if intro_remainder:
res.append(new_markdown_cell(intro_remainder))
return res
示例11: export
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def export(combined_nb: NotebookNode, output_file: Path, pdf=False,
template_file=None):
resources = {}
resources['unique_key'] = 'combined'
resources['output_files_dir'] = 'combined_files'
log.info('Converting to %s', 'pdf' if pdf else 'latex')
exporter = MyLatexPDFExporter() if pdf else MyLatexExporter()
if template_file is not None:
exporter.template_file = str(template_file)
writer = FilesWriter(build_directory=str(output_file.parent))
output, resources = exporter.from_notebook_node(combined_nb, resources)
writer.write(output, resources, notebook_name=output_file.stem)
示例12: from_nbnode
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def from_nbnode(value):
"""Recursively convert NotebookNode to dict."""
if isinstance(value, nbf.NotebookNode):
return {k: from_nbnode(v) for k, v in value.items()}
return value
示例13: export
# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import NotebookNode [as 别名]
def export(exporter, nb, **kw):
"""
Export a notebook object using specific exporter class.
Parameters
----------
exporter : :class:`~nbconvert.exporters.exporter.Exporter` class or instance
Class or instance of the exporter that should be used. If the
method initializes its own instance of the class, it is ASSUMED that
the class type provided exposes a constructor (``__init__``) with the same
signature as the base Exporter class.
nb : :class:`~nbformat.NotebookNode`
The notebook to export.
config : config (optional, keyword arg)
User configuration instance.
resources : dict (optional, keyword arg)
Resources used in the conversion process.
Returns
-------
tuple
output : str
The resulting converted notebook.
resources : dictionary
Dictionary of resources used prior to and during the conversion
process.
"""
#Check arguments
if exporter is None:
raise TypeError("Exporter is None")
elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
raise TypeError("exporter does not inherit from Exporter (base)")
if nb is None:
raise TypeError("nb is None")
#Create the exporter
resources = kw.pop('resources', None)
if isinstance(exporter, Exporter):
exporter_instance = exporter
else:
exporter_instance = exporter(**kw)
#Try to convert the notebook using the appropriate conversion function.
if isinstance(nb, NotebookNode):
output, resources = exporter_instance.from_notebook_node(nb, resources)
elif isinstance(nb, string_types):
output, resources = exporter_instance.from_filename(nb, resources)
else:
output, resources = exporter_instance.from_file(nb, resources)
return output, resources