本文整理汇总了Python中nbconvert.HTMLExporter.from_filename方法的典型用法代码示例。如果您正苦于以下问题:Python HTMLExporter.from_filename方法的具体用法?Python HTMLExporter.from_filename怎么用?Python HTMLExporter.from_filename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nbconvert.HTMLExporter
的用法示例。
在下文中一共展示了HTMLExporter.from_filename方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_iab_main
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import from_filename [as 别名]
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)
示例2: nb2html
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import from_filename [as 别名]
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
示例3: convert_notebooks
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import from_filename [as 别名]
def convert_notebooks(in_directory, html_directory, static_directory):
dl = DictLoader({
'post.tpl':
"""
{%- extends 'basic.tpl' -%}
{% block body %}---
title: {{nb.metadata['title']}}
notebook: {{resources['metadata']['path']}}/{{resources['metadata']['name']}}.ipynb
date: {{nb.metadata['date']}}
---
{{ super() }}
{% endblock body %}
"""
})
c = Config()
c.HTMLExporter.preprocessors = [
'nbconvert.preprocessors.ExtractOutputPreprocessor'
]
html_exporter = HTMLExporter(config=c, extra_loaders=[dl])
html_exporter.template_file = 'post.tpl'
writer = FilesWriter(build_directory=html_directory)
for notebook_file in glob(path.join(in_directory, '*.ipynb')):
out_name, _ = path.splitext(path.basename(notebook_file))
out_name = out_name.lower().replace(' ', '-')
print('Converting {}'.format(notebook_file))
(body, resources) = html_exporter.from_filename(
notebook_file,
resources={'output_files_dir': out_name})
writer.write(body, resources, notebook_name=out_name)
shutil.rmtree(path.join(static_directory, out_name), True)
rename(path.join(html_directory, out_name),
path.join(static_directory, out_name))
示例4: len
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.HTMLExporter import from_filename [as 别名]
import re
from nbconvert import HTMLExporter
if __name__ == '__main__':
assert len(sys.argv) == 3, \
'./convert_nb_to_html.py [notebook filename] [html output filename]'
input_file = sys.argv[1]
output_file = sys.argv[2]
base_dir = os.path.dirname(os.path.abspath(input_file))
def to_base64(match):
full_path = os.path.join(base_dir, match.group(0))
print('Replacing ' + full_path)
with open(full_path, 'rb') as img:
enc = base64.b64encode(img.read()).decode()
ext = os.path.splitext(full_path)[1]
return 'data:image/' + ext[1:] + ';base64,' + enc
html_exporter = HTMLExporter()
body, resources = html_exporter.from_filename(input_file)
img_regex = r"(?<=img src=\")[^\"]*"
body = re.sub(img_regex, to_base64, body)
with open(output_file, 'w') as f:
f.write(body)
示例5: read
# 需要导入模块: from nbconvert import HTMLExporter [as 别名]
# 或者: from nbconvert.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