當前位置: 首頁>>代碼示例>>Python>>正文


Python HTMLExporter.from_filename方法代碼示例

本文整理匯總了Python中nbconvert.exporters.HTMLExporter.from_filename方法的典型用法代碼示例。如果您正苦於以下問題:Python HTMLExporter.from_filename方法的具體用法?Python HTMLExporter.from_filename怎麽用?Python HTMLExporter.from_filename使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在nbconvert.exporters.HTMLExporter的用法示例。


在下文中一共展示了HTMLExporter.from_filename方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath, start=0, end=None, preprocessors=[], template=None):
    """Return the HTML from a Jupyter Notebook
    """
    template_file = 'basic'
    extra_loaders = []
    if template:
        extra_loaders.append(jinja2.FileSystemLoader([os.path.dirname(template)]))
        template_file = os.path.basename(template)

    config = get_config()
    config.update({'CSSHTMLHeaderTransformer': {
                        'enabled': True,
                        'highlight_class': '.highlight-ipynb'},
                     'SubCell': {
                        'enabled':True,
                        'start':start,
                        'end':end}})
    exporter = HTMLExporter(config=config,
                            template_file=template_file,
                            extra_loaders=extra_loaders,
                            filters={'highlight2html': custom_highlighter},
                            preprocessors=[SubCell] + preprocessors)

    config.CSSHTMLHeaderPreprocessor.highlight_class = " .highlight pre "
    content, info = exporter.from_filename(filepath)

    return content, info
開發者ID:danielfrg,項目名稱:pelican-ipynb,代碼行數:29,代碼來源:core.py

示例2: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath,
                           start=0,
                           end=None,
                           template=None):
    """Return the HTML from a Jupyter Notebook
    """
    preprocessors_ = [SubCell]

    template_file = "basic"
    extra_loaders = []
    if template:
        extra_loaders.append(
            jinja2.FileSystemLoader([os.path.dirname(template)]))
        template_file = os.path.basename(template)

    # Load the user's nbconvert configuration
    app = NbConvertApp()
    app.load_config_file()

    app.config.update({
        # This Preprocessor changes the pygments css prefixes
        # from .highlight to .highlight-ipynb
        "CSSHTMLHeaderPreprocessor": {
            "enabled": True,
            "highlight_class": ".highlight-ipynb",
        },
        "SubCell": {
            "enabled": True,
            "start": start,
            "end": end
        },
    })

    # Overwrite Custom jinja filters
    # This is broken right now so needs fix from below
    # https://github.com/jupyter/nbconvert/pull/877
    filters = {
        "highlight_code": custom_highlight_code
    }

    exporter = HTMLExporter(
        config=app.config,
        template_file=template_file,
        extra_loaders=extra_loaders,
        filters=filters,
        preprocessors=preprocessors_,
    )
    content, info = exporter.from_filename(filepath)

    # Fix for nbconvert bug
    # content = content.replace("<pre>", '<pre class="highlight highlight-ipynb">')
    # end-fix

    # Since we make a Markdown file we need to remove empty lines and strip
    content = "\n".join([line.rstrip() for line in content.split("\n") if line.rstrip()])

    return content, info
開發者ID:danielfrg,項目名稱:danielfrg.github.io-source,代碼行數:59,代碼來源:convert.py

示例3: render_notebook

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
    def render_notebook(self, filename, site=None, data=None, lang=None, post=None):
        c = Config(self.site.config['IPYNB_CONFIG'])
        export_html = HTMLExporter(config=c)
        (notebook_raw, _) = export_html.from_filename(filename)

        # The raw HTML contains garbage (scripts and styles). Extract only div id=notebook-container and children
        notebook_html = lxml.html.fromstring(notebook_raw)
        notebook_code = lxml.html.tostring(notebook_html.xpath('//*[@id="notebook-container"]')[0], encoding='unicode')

        return notebook_code, [filename]
開發者ID:getnikola,項目名稱:plugins,代碼行數:12,代碼來源:notebook_shortcode.py

示例4: convert_ipynb_to_html

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def convert_ipynb_to_html(notebook_file, html_file):
    """
    Convert the given `notebook_file` to HTML and
    write it to `html_file`.
    """

    # set a high timeout for datasets with a large number of features
    report_config = Config({'ExecutePreprocessor': {'enabled': True,
                                                    'timeout': 600},
                            'HTMLExporter': {'template_path': [template_path],
                                             'template_file': 'report.tpl'}})

    exportHtml = HTMLExporter(config=report_config)
    output, resources = exportHtml.from_filename(notebook_file)
    open(html_file, mode='w', encoding='utf-8').write(output)
開發者ID:WeilamChung,項目名稱:rsmtool,代碼行數:17,代碼來源:report.py

示例5: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath):
    """Convert ipython notebook to html
    Return: html content of the converted notebook
    """
    config = Config({"CSSHTMLHeaderTransformer": {"enabled": True, "highlight_class": ".highlight-ipynb"}})
    exporter = HTMLExporter(config=config, template_file="basic", filters={"highlight2html": custom_highlighter})
    content, info = exporter.from_filename(filepath)

    if BeautifulSoup:
        soup = BeautifulSoup(content, "html.parser")
        for i in soup.findAll("div", {"class": "input"}):
            if i.findChildren()[1].find(text="#ignore") is not None:
                i.extract()
        content = soup.decode(formatter=None)

    return content, info
開發者ID:koldunovn,項目名稱:earthpy.org,代碼行數:18,代碼來源:core.py

示例6: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath):
    """Convert ipython notebook to html
    Return: html content of the converted notebook
    """
    config = Config({'CSSHTMLHeaderTransformer': {'enabled': True,
                                                  'highlight_class': '.highlight-ipynb'}})

    config.HTMLExporter.preprocessors = [HtmlLinksPreprocessor]
    config.HtmlLinksPreprocessor['enabled'] = True

    path = os.path.dirname(os.path.realpath(__file__))
    exporter = HTMLExporter(config=config, template_file='no_code',
                            template_path=['.', path + '/../../../scripts/'],
                            filters={'highlight2html': custom_highlighter})
    content, info = exporter.from_filename(filepath)

    return content, info
開發者ID:Huaguiyuan,項目名稱:phys_codes,代碼行數:19,代碼來源:core.py

示例7: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath):
    """Convert ipython notebook to html
    Return: html content of the converted notebook
    """
    config = Config({'CSSHTMLHeaderTransformer': {'enabled': True,
                     'highlight_class': '.highlight-ipynb'}})
    exporter = HTMLExporter(config=config, template_file='basic')
    exporter.register_filter('markdown2html', filters.markdown2html_pandoc)

    content, info = exporter.from_filename(filepath)

    soup = BeautifulSoup(content, "html.parser")
    for i in soup.findAll("div", {"class": "input"}):
        if i.findChildren()[1].find(text='#ignore') is not None:
            i.extract()
    content = soup.decode(formatter=None)

    return content, info
開發者ID:pawel-n,項目名稱:pelican-jupyter,代碼行數:20,代碼來源:core.py

示例8: nb_to_html

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def nb_to_html(nb_path):
    """convert notebook to html"""
    exporter = HTMLExporter(template_file='full')
    output, resources = exporter.from_filename(nb_path)
    header = output.split('<head>', 1)[1].split('</head>',1)[0]
    body = output.split('<body>', 1)[1].split('</body>',1)[0]

    # http://imgur.com/eR9bMRH
    header = header.replace('<style', '<style scoped="scoped"')
    header = header.replace('body {\n  overflow: visible;\n  padding: 8px;\n}\n', '')
    header = header.replace("code,pre{", "code{")

    header = header.replace('\n', '')
    comp = re.compile('<style.*?</style>', re.MULTILINE)
    header = comp.sub('', header)

    # Filter out styles that conflict with the sphinx theme.
    filter_strings = [
        'navbar',
        'body{',
        'alert{',
        'uneditable-input{',
        'collapse{',
    ]
    filter_strings.extend(['h%s{' % (i+1) for i in range(6)])

    line_begin_strings = [
        'pre{',
        'p{margin'
        ]

    header_lines = filter(
        lambda x: not any([s in x for s in filter_strings]), header.split('\n'))
    header_lines = filter(
        lambda x: not any([x.startswith(s) for s in line_begin_strings]), header_lines)

    header = '\n'.join(header_lines)

    # fix wrong static links to headers
    body = body.replace('class="anchor-link"', 'class="headerlink"')

    # concatenate raw html lines
    lines = ['<div class="ipynotebook">', header, body, '</div>']
    return '\n'.join(lines)
開發者ID:dwhswenson,項目名稱:openpathsampling,代碼行數:46,代碼來源:notebook_sphinxext.py

示例9: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath):
    """Convert ipython notebook to html
    Return: html content of the converted notebook
    """
    config = Config({'CSSHTMLHeaderTransformer': {'enabled': True,
                     'highlight_class': '.highlight-ipynb'}})
    exporter = HTMLExporter(config=config, template_file='basic',
                            filters={'highlight2html': custom_highlighter})

    content, info = exporter.from_filename(filepath)

    if BeautifulSoup:
        soup = BeautifulSoup(content)
        for i in soup.findAll("div", {"class" : "input"}):
            if i.findChildren()[1].find(text='#ignore') is not None:
                i.extract()
        content = soup

    return content, info
開發者ID:nekonokoi,項目名稱:pelican-ipynb,代碼行數:21,代碼來源:core.py

示例10: get_html_from_filepath

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
def get_html_from_filepath(filepath, start=0, end=None):
    """Convert ipython notebook to html
    Return: html content of the converted notebook
    """
    config = Config({'CSSHTMLHeaderTransformer': {'enabled': True,
                     'highlight_class': '.highlight-ipynb'},
                     'SubCell': {'enabled':True, 'start':start, 'end':end}})
    exporter = HTMLExporter(config=config, template_file='basic',
                            filters={'highlight2html': custom_highlighter},
                            preprocessors=[SubCell])
    content, info = exporter.from_filename(filepath)

    if BeautifulSoup:
        soup = BeautifulSoup(content, 'html.parser')
        for i in soup.findAll('div', {'class': 'input'}):
            if i.findChildren()[1].find(text='#ignore') is not None:
                i.extract()
        content = soup.decode(formatter=None)

    return content, info
開發者ID:Sandeep42,項目名稱:Sandeep42.github.io-source,代碼行數:22,代碼來源:core.py

示例11: read

# 需要導入模塊: from nbconvert.exporters import HTMLExporter [as 別名]
# 或者: from nbconvert.exporters.HTMLExporter import from_filename [as 別名]
    def read(self, filepath):
        metadata = {}

        # Files
        filedir = os.path.dirname(filepath)
        filename = os.path.basename(filepath)
        metadata_filename = filename.split('.')[0] + '.ipynb-meta'
        metadata_filepath = os.path.join(filedir, metadata_filename)

        # Load metadata
        if os.path.exists(metadata_filepath):
            # Metadata is on a external file, process using Pelican MD Reader
            md_reader = MarkdownReader(self.settings)
            _content, metadata = md_reader.read(metadata_filepath)
        else:
            # Load metadata from ipython notebook file
            ipynb_file = open(filepath)
            metadata = json.load(ipynb_file)['metadata']

            # Fix metadata to pelican standards
            for key, value in metadata.items():
                del metadata[key]
                key = key.lower()
                metadata[key] = self.process_metadata(key, value)
        metadata['ipython'] = True

        # Convert ipython notebook to html
        config = Config({'CSSHTMLHeaderTransformer': {'enabled': True,
                         'highlight_class': '.highlight-ipynb'}})
        exporter = HTMLExporter(config=config, template_file='basic',
                                filters={'highlight2html': custom_highlighter})

        content, info = exporter.from_filename(filepath)

        if BeautifulSoup:
            soup = BeautifulSoup(content)
            for i in soup.findAll("div", {"class" : "input"}):
                if i.findChildren()[1].find(text='#ignore') is not None:
                    i.extract()
        else:
            soup = content

        # Process using Pelican HTMLReader
        content = '<body>{0}</body>'.format(soup)  # So Pelican HTMLReader works
        parser = MyHTMLParser(self.settings, filename)
        parser.feed(content)
        parser.close()
        body = parser.body
        if ('IPYNB_USE_META_SUMMARY' in self.settings.keys() and \
          self.settings['IPYNB_USE_META_SUMMARY'] == False) or \
          'IPYNB_USE_META_SUMMARY' not in self.settings.keys():
            metadata['summary'] = parser.summary

        def filter_css(style_text):
            '''
            HACK: IPython returns a lot of CSS including its own bootstrap.
            Get only the IPython Notebook CSS styles.
            '''
            index = style_text.find('/*!\n*\n* IPython notebook\n*\n*/')
            if index > 0:
                style_text = style_text[index:]
            index = style_text.find('/*!\n*\n* IPython notebook webapp\n*\n*/')
            if index > 0:
                style_text = style_text[:index]

            style_text = re.sub(r'color\:\#0+(;)?', '', style_text)
            style_text = re.sub(r'\.rendered_html[a-z0-9,._ ]*\{[a-z0-9:;%.#\-\s\n]+\}', '', style_text)

            return '<style type=\"text/css\">{0}</style>'.format(style_text)

        ipython_css = '\n'.join(filter_css(css_style) for css_style in info['inlining']['css'])
        body = ipython_css + body + LATEX_CUSTOM_SCRIPT

        return body, metadata
開發者ID:Neurita,項目名稱:pelican-plugins,代碼行數:76,代碼來源:ipynb.py


注:本文中的nbconvert.exporters.HTMLExporter.from_filename方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。