• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python nbconvert.HTMLExporter类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nbconvert.HTMLExporter的典型用法代码示例。如果您正苦于以下问题:Python HTMLExporter类的具体用法?Python HTMLExporter怎么用?Python HTMLExporter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HTMLExporter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: nb_to_html

def nb_to_html(root, template='basic', version=4, timeout=600, kernel='python3'):
    '''
    This functions executes a Jupyter notebook and creates the related
    HTML file.

    Args:
        root (str): name of the file without the .ipynb extension
        template (str): name of the template (to be in the current folder as template.tpl)
        version (int): version of the notebook
        timeout (float): maximum time spent per cell
        kernel (str)

    Returns:
        None

    The function executes root.ipynb into root_exe.ipynb and creates the file root.html.
    '''
    with open(root + '.ipynb') as f:
        nb = nbformat.read(f, as_version=version)

    ep = ExecutePreprocessor(timeout=timeout, kernel_name=kernel)
    ep.preprocess(nb, {'metadata': {'path': '.'}})

    with open(root + '_exe.ipynb', 'wt') as f:
        nbformat.write(nb, f)

    html_exporter = HTMLExporter()
    html_exporter.template_file = template

    with open(root + '_exe.ipynb', mode='r') as f:
        notebook = nbformat.reads(''.join(f.readlines()), as_version=version)
        (body, _) = html_exporter.from_notebook_node(notebook)
        codecs.open(root + '.html', 'w', encoding='utf-8').write(body)
开发者ID:PetitLepton,项目名称:design,代码行数:33,代码来源:nb_to_report.py


示例2: bundle_notebook

def bundle_notebook(vid, fileid):
    """Return a file from the bundle"""
    from ambry.orm.file import File
    import nbformat
    from traitlets.config import Config
    from nbconvert import HTMLExporter

    b = aac.library.bundle(vid)

    nbfile = b.build_source_files.file_by_id(fileid)

    notebook = nbformat.reads(nbfile.unpacked_contents, as_version=4)

    html_exporter = HTMLExporter()
    html_exporter.template_file = 'basic'

    (body, resources) = html_exporter.from_notebook_node(notebook)

    cxt = dict(
        vid=vid,
        b=b,
        fileid=fileid,
        nbfile=nbfile,
        notebooks=b.build_source_files.list_records(File.BSFILE.NOTEBOOK),
        notebook=notebook,
        notebook_html=body,
        **aac.cc

    )

    return aac.render('bundle/notebook.html', **cxt)
开发者ID:CivicKnowledge,项目名称:ambry-ui,代码行数:31,代码来源:views.py


示例3: build_iab_main

def build_iab_main(input_dir, output_dir, out_format, ext, css=None):
    """ Convert md sources to readable book content, maintaining dir structure.

        A few additional processing steps happen here:
         * Add Table of Contents to the top of each section.
         * Create links from sha1 aliases.

        Parameters
        ----------
        input_dir : str
            Root path for the markdown files.
        output_dir : str
            Root path for the output files.
        out_format : str
            The ipymd format that output files should be written in (for example,
            ``notebook``).
        ext : str
            The extension to use for output files.

    """
    # Walk the input root directory. We only care about root and files
    # inside this loop (nothing happens with dirs).
    for unit_number, (unit, chapters) in enumerate(input_dir):
        # Iterate over the files in the current root.
        if unit_number == 0:
            unit_path = ''
        else:
            unit_path = str(unit_number) + '/'
        for chapter_number, content_md in enumerate(chapters):
            if chapter_number == 0:
                chapter_path = 'index'
            else:
                chapter_path = str(chapter_number)
            path = '%s%s' % (unit_path, chapter_path)
            # Convert it from markdown
            output_s = ipymd.convert(content_md, from_='markdown', to='notebook')
            # define the output filepath
            output_fp = get_output_fp(output_dir, path, ext)
            try:
                os.makedirs(os.path.split(output_fp)[0])
            except OSError:
                pass

            # write the output ipynb
            nbformat.write(output_s, output_fp)

    if out_format == 'html' or out_format == 's3':
        c = Config()
        c.ExecutePreprocessor.timeout = 600
        html_exporter = HTMLExporter(preprocessors=['nbconvert.preprocessors.execute.ExecutePreprocessor'],
                                     config=c)

        for root, dirs, files in os.walk(output_dir):
            if css:
                shutil.copy(css, os.path.join(root, 'custom.css'))
            for f in files:
                html_out, _ = html_exporter.from_filename(os.path.join(root, f))
                output_fn = os.path.splitext(f)[0] + ext
                output_fp = os.path.join(root, output_fn)
                open(output_fp, 'w').write(html_out)
开发者ID:gregcaporaso,项目名称:build-iab,代码行数:60,代码来源:util.py


示例4: execute

    def execute(self):
        print("Cleaning lowfat/reports/html ...")
        old_reports = os.listdir("lowfat/reports/html")
        for old_report in old_reports:
            print("- Removing lowfat/reports/html/{}".format(old_report))
            os.remove("lowfat/reports/html/{}".format(old_report))
        print("Cleaning of lowfat/reports/html is complete.")

        notebook_filenames = os.listdir("lowfat/reports")

        for notebook_filename in notebook_filenames:
            if not notebook_filename.endswith(".ipynb"):
                continue

            print("Processing lowfat/reports/{}".format(notebook_filename))

            # Based on Executing notebooks, nbconvert Documentation by Jupyter Development Team.
            # https://nbconvert.readthedocs.io/en/latest/execute_api.html
            with open("lowfat/reports/{}".format(notebook_filename)) as file_:
                notebook = nbformat.read(file_, as_version=4)

                # Kernel is provided by https://github.com/django-extensions/django-extensions/
                execute_preprocessor = ExecutePreprocessor(timeout=600, kernel_name='django_extensions')
                execute_preprocessor.preprocess(notebook, {'metadata': {'path': '.'}})

                html_exporter = HTMLExporter()
                html_exporter.template_file = 'basic'

                (body, dummy_resources) = html_exporter.from_notebook_node(notebook)

                with open('lowfat/reports/html/{}.html'.format(notebook_filename), 'wt') as file_:
                    file_.write(body)
开发者ID:softwaresaved,项目名称:fat,代码行数:32,代码来源:report.py


示例5: update_jupyter

 def update_jupyter(self, s, keywords):
     '''Update @jupyter node in the vr pane.'''
     pc = self
     c = pc.c
     if pc.must_change_widget(QtWebKitWidgets.QWebView):
         # g.trace('===== instantiating QWebView')
         w = QtWebKitWidgets.QWebView()
         n = c.config.getInt('qweb_view_font_size')
         if n:
             settings = w.settings()
             settings.setFontSize(settings.DefaultFontSize, n)
         pc.embed_widget(w)
         assert(w == pc.w)
     else:
         w = pc.w
     url = g.getUrlFromNode(c.p)
     if url and nbformat:
         s = urlopen(url).read().decode()
         try:
             nb = nbformat.reads(s, as_version=4)
             e = HTMLExporter()
             (s, junk_resources) = e.from_notebook_node(nb)
         except nbformat.reader.NotJSONError:
             # Assume the result is html.
             pass
     elif url:
         s = 'can not import nbformt: %r' % url
     else:
         s = g.u('')
     if isQt5:
         w.hide() # This forces a proper update.
     w.setHtml(s)
     w.show()
     c.bodyWantsFocusNow()
开发者ID:satishgoda,项目名称:leo-editor,代码行数:34,代码来源:viewrendered.py


示例6: export_notebook_to_html

def export_notebook_to_html(notebook_fp, output_dir):
    nb = read_in_notebook(notebook_fp)
    html_exporter = HTMLExporter()
    body, resources = html_exporter.from_notebook_node(nb)
    _, notebook_name, _ = get_file_name_pieces(notebook_fp)
    out_fp = make_file_path(output_dir, notebook_name, ".html")
    with open(out_fp, "w", encoding="utf8") as f:
        f.write(body)
开发者ID:christineyi,项目名称:jupyter-genomics,代码行数:8,代码来源:notebook_runner.py


示例7: export_notebook_to_html

def export_notebook_to_html(notebook, datestamp, mark_as_latest=True):
    html_exporter = HTMLExporter()
    html, _resources = html_exporter.from_notebook_node(notebook)
    output_path = get_monitoring_notebook_output_path(datestamp, ext='html')
    with open(output_path, 'wt') as outfile:
        outfile.write(html)
    if mark_as_latest:
        latest_notebook_path = get_monitoring_notebook_output_path('latest', ext='html')
        copyfile(output_path, latest_notebook_path)
开发者ID:adaptive-learning,项目名称:robomission,代码行数:9,代码来源:export_monitoring_notebook.py


示例8: output_HTML

def output_HTML(read_file, output_file):
    from nbconvert import HTMLExporter
    import codecs
    import nbformat
    exporter = HTMLExporter()
    # read_file is '.ipynb', output_file is '.html'
    output_notebook = nbformat.read(read_file, as_version=4)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_file, 'w', encoding='utf-8').write(output)
开发者ID:BenJamesbabala,项目名称:Wind-Speed-Analysis,代码行数:9,代码来源:lib_loader.py


示例9: convert_nb_html

def convert_nb_html(nb):
    """
    Convert a notebooks output to HTML
    """
    nb = run_notebook(nb)
    config = Config({'HTMLExporter': {'default_template': 'basic'}})
    exportHtml = HTMLExporter(config=config)
    html, resources = exportHtml.from_notebook_node(nb)
    soup = BeautifulSoup(html)
    filters = ["output", "text_cell_render border-box-sizing rendered_html"]
    return ''.join(map(str, soup.findAll("div", {"class": filters})))
开发者ID:zimmerst,项目名称:Flasked-Notebooks,代码行数:11,代码来源:run_ipynb.py


示例10: write_html

 def write_html(self):
     print("writing", self.html)
     html_exporter = HTMLExporter()
     html_exporter.template_file = 'full'
     # do a deeo copy to any chance of overwriting the original notebooks
     content = copy.deepcopy(self.content)
     content.cells = content.cells[2:-1]
     content.cells[0].source = "# " + self.numbered_title
     (body, resources) = html_exporter.from_notebook_node(content)
     with open(self.html, 'w') as f:
         f.write(body)
开发者ID:jckantor,项目名称:CBE20255,代码行数:11,代码来源:__main__.py


示例11: render

def render(file):
    """Generate the result HTML."""
    fp = file.open()
    content = fp.read()
    fp.close()

    notebook = nbformat.reads(content.decode('utf-8'), as_version=4)

    html_exporter = HTMLExporter()
    html_exporter.template_file = 'basic'
    (body, resources) = html_exporter.from_notebook_node(notebook)
    return body, resources
开发者ID:hachreak,项目名称:invenio-previewer,代码行数:12,代码来源:ipynb.py


示例12: preview

    def preview(self, filepath):
        """
        Preview a notebook store in the Storage
        :param filepath: Path to the notebook to preview on Storage

        :return a notebook in html format
        """
        self.log.debug("Make a Html preview of notebook '%s'" % filepath);
        nb = self.read(filepath);
        html_conveter = HTMLExporter()
        (body, resources) = html_conveter.from_notebook_node(nb)
        return body;
开发者ID:Valdimus,项目名称:nbshared,代码行数:12,代码来源:storage.py


示例13: _nbconvert_to_html

    def _nbconvert_to_html(cls, page):
        """Use nbconvert to render a notebook as HTML.
        
        Strip the headings from the first markdown cell to avoid showing the 
        page title twice on the blog.
        """
        if page["cells"] and page["cells"][0]["cell_type"] == "markdown":
            source = page["cells"][0]["source"]
            page["cells"][0]["source"] = re.sub("#+.*\n", "", source, re.MULTILINE)

        e = HTMLExporter()
        e.template_file = "basic"
        return e.from_notebook_node(page)[0]
开发者ID:parente,项目名称:blog,代码行数:13,代码来源:generate.py


示例14: post

        def post(self): 
          id=self.get_argument("path")
          print id
          db=create_engine('postgresql://postgres:[email protected]/ishtar')
        
          fileContent=reads_base64(pgquery.get_file(db, "share", id, include_content=True)['content'])
          #notebook= nbformat.reads(fileContent, as_version=4)
          notebook=fileContent
          db.dispose()
          html_exporter = HTMLExporter()
          html_exporter.template_file = 'basic'

          (body, resources) = html_exporter.from_notebook_node(notebook)
          self.write(body)
开发者ID:albanatita,项目名称:GilgameshServer,代码行数:14,代码来源:serverHub.py


示例15: as_html

    def as_html(self, file):
        with File().open(file) as fp:
            notebook = nbformat.reads(fp.read().decode(), as_version=4)

        exporter = HTMLExporter()
        #exporter.template_file = 'basic'

        (body, resources) = exporter.from_notebook_node(notebook)

        def stream():
            cherrypy.response.headers['Content-Type'] = 'text/html'
            yield body

        return stream
开发者ID:OpenChemistry,项目名称:mongochemserver,代码行数:14,代码来源:rest.py


示例16: nb2html

def nb2html(nb_filepath):
    """
    Convert notebook to html string.

    Args:
        nb_filepath (str): Path of notbook file

    Returns:
        (str): HMTL of converted notebook.
    """
    # Save notebook
    exporter = HTMLExporter()
    exporter.template_file = 'basic'
    output, resources = exporter.from_filename(nb_filepath)
    return output
开发者ID:peterroelants,项目名称:peterroelants.github.io,代码行数:15,代码来源:notebook_convert.py


示例17: NarrativeExporter

class NarrativeExporter():
    def __init__(self):
        c = Config()
        c.HTMLExporter.preprocessors = [NarrativePreprocessor]
        c.TemplateExporter.template_path = ['.', self._narrative_template_path()]
        c.CSSHTMLHeaderPreprocessor.enabled = True
        self.html_exporter = HTMLExporter(config=c)
        self.html_exporter.template_file = 'narrative'
        self.ws_client = Workspace(URLS.workspace)
        self.narr_fetcher = NarrativeIO()

    def _narrative_template_path(self):
        return os.path.join(os.environ.get('NARRATIVE_DIR', '.'), 'src', 'biokbase', 'narrative', 'exporter', 'templates')

    def export_narrative(self, narrative_ref, output_file):
        nar = self.narr_fetcher.read_narrative(narrative_ref)

        nar = nar['data']

        # # 1. Get the narrative object
        # # (put in try/except)
        # # (should also raise an error if narrative is not public)
        # nar = self.ws_client.get_objects([{'ref': narrative_ref}])

        # # put in separate try/except
        # nar = nar[0]['data']

        # 2. Convert to a notebook object
        kb_notebook = nbformat.reads(json.dumps(nar), as_version=4)

        # 3. make the thing
        (body, resources) = self.html_exporter.from_notebook_node(kb_notebook)

        with open(output_file, 'w') as output_html:
            output_html.write(body)
开发者ID:briehl,项目名称:narrative,代码行数:35,代码来源:exporter.py


示例18: post_save

def post_save(model, os_path, contents_manager):
    """post-save hook for converting notebooks to .py scripts"""
    if model['type'] != 'notebook':
        return # only do this for notebooks
    if 'Untitled' in os_path:
        return # do not save untitled notebooks

    output_file_path = construct_output_py_file_path(os_path, skip_if_exists=False)
    output_html_path = construct_output_html_file_path(os_path, skip_if_exists=False)
    notebook_data = get_notebook_data(os_path)
    write_notebook_data_to_py(notebook_data, output_file_path)
    exporter = HTMLExporter()
    output_notebook = nbformat.read(os_path, as_version=4)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_html_path, 'w', encoding='utf-8').write(output) 
    print (output_file_path, "was successfully saved")
开发者ID:drschwenk,项目名称:my_configs,代码行数:16,代码来源:jupyter_notebook_config.py


示例19: main

def main(ipynb, kernel_name):
    print("running %s" % ipynb)
    nb = read(ipynb, as_version=4)

    config = get_config()
    config.BokehExecutePreprocessor.kernel_name = kernel_name
    print(config)
    ep = BokehExecutePreprocessor(config=config)
    ep.preprocess(nb, {'metadata': {'path': './'}})

    exportHtml = HTMLExporter()
    (body, resources) = exportHtml.from_notebook_node(nb)

    outfile = ipynb + ".html"
    open(outfile, 'w').write(body)
    print("wrote %s" % outfile)
开发者ID:brianpanneton,项目名称:bokeh,代码行数:16,代码来源:nbexecuter.py


示例20: notebook2html

def notebook2html(index: dict, in_dir: str, templates: dict, host: str, 
                  out_dir: str, content_dirname: str):
    """
    Convert jupyter notebook to html. See relevant docs here:
    https://nbconvert.readthedocs.io/en/latest/nbconvert_library.html#Quick-overview
    
    Possible enhancements:
    - extract images from notebook
    - render from url
    """
    new_index = []

    for item in index:
        if item.get('format') == 'ipynb':
            
            # Render notebook as html
            in_fp = f'{in_dir}/{item["in_pth"]}'
            notebook = nbformat.read(in_fp, as_version=4)
            html_exporter = HTMLExporter()
            html_exporter.template_file = 'basic'
            nb_html, resources = html_exporter.from_notebook_node(notebook)
            
            # Render navbar
            navbar = templates['navbar'].render()
            
            # Render comments section
            filename = ntpath.basename(in_fp)[:-len('.ipynb')]
            page = {'url': f'{host}/{content_dirname}/{filename}.html',
                    'identifier': filename}
            comments = templates['comments'].render(page=page)

            # Render entire page
            html = {'navbar': navbar, 'notebook': nb_html, 'comments': comments}
            body = templates['notebook'].render(html=html)
            
            # Write html to file
            out_fp = f'{out_dir}/{filename}.html'
            data2file(body, out_fp)
            
            # Add html path to index
            out_pth = f'./{content_dirname}/{filename}.html'
            item_new = add2dict('out_pth', out_pth, item)
        
        else:
            item_new = item
        new_index.append(item_new)
    return new_index
开发者ID:a-martyn,项目名称:website,代码行数:47,代码来源:utils.py



注:本文中的nbconvert.HTMLExporter类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python exporters.HTMLExporter类代码示例发布时间:2022-05-27
下一篇:
Python nba_py._get_json函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap