当前位置: 首页>>代码示例>>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;未经允许,请勿转载。