dsc*_*ose 5 html python restructuredtext docutils
我正在尝试使用 docutils 包将 ReST 转换为 HTML。这个答案简洁地使用了 docutils 的publish_*便利功能来一步实现这一点。我想转换的 ReST 文档有多个部分,我想在生成的 HTML 中将它们分开。因此,我想分解这个过程:
这是我正在努力解决的第三步。以下是我如何执行第一步和第二步:
from docutils import utils
from docutils.frontend import OptionParser
from docutils.parsers.rst import Parser
# preamble
rst = '*NB:* just an example.' # will actually have many sections
path = 'some.url.com'
settings = OptionParser(components=(Parser,)).get_default_values()
# step 1
document = utils.new_document(path, settings)
Parser().parse(rst, document)
# step 2
for node in document:
do_something_with(node)
# step 3: Help!
for node in filtered(document):
print(convert_to_html(node))
Run Code Online (Sandbox Code Playgroud)
我找到了HTMLTranslator班级和Publisher班级。它们似乎相关,但我正在努力寻找好的文档。我应该如何实现该convert_to_html功能?
我的问题是我试图在太低的级别上使用 docutils 包。他们为这种事情提供了一个接口:
from docutils.core import publish_doctree, publish_from_doctree
rst = '*NB:* just an example.'
# step 1
tree = publish_doctree(rst)
# step 2
# do something with the tree
# step 3
html = publish_from_doctree(tree, writer_name='html').decode()
print(html)
Run Code Online (Sandbox Code Playgroud)
第一步现在要简单得多。话虽如此,我对结果还是有点不满意;我意识到我真正想要的是一个publish_node函数。如果您知道更好的方法,请发布。
我还应该注意,我还没有设法在 Python 3 中使用它。
我实际上试图做的是从文档树中提取所有侧边栏元素,以便它们可以单独处理到文章的主体中。这不是docutils旨在解决的用例。因此没有publish_node功能。
一旦我意识到这一点,正确的方法就很简单了:
docutils.BeautifulSoup。这是完成工作的代码:
from docutils.core import publish_parts
from bs4 import BeautifulSoup
rst = get_rst_string_from_somewhere()
# get just the body of an HTML document
html = publish_parts(rst, writer_name='html')['html_body']
soup = BeautifulSoup(html, 'html.parser')
# docutils wraps the body in a div with the .document class
# we can just dispose of that div altogether
wrapper = soup.select('.document')[0]
wrapper.unwrap()
# knowing that docutils gives all sidebar elements the
# .sidebar class makes extracting those elements easy
sidebar = ''.join(tag.extract().prettify() for tag in soup.select('.sidebar'))
# leaving the non-sidebar elements as the document body
body = soup.prettify()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |