python - 我可以直接调用 sphinx.parsers.Parser() 并解析 reST 的片段吗?
问题描述
我需要将一个独立的 reST 内容片段解析为一个 doctree(供以后处理)。我可以很容易地通过 docutils 做到这一点,例如:
# ref: http://stackoverflow.com/questions/12883428/
import docutils.nodes
import docutils.parsers.rst
import docutils.utils
def parse_rst(text: str) -> docutils.nodes.document:
parser = docutils.parsers.rst.Parser()
components = (docutils.parsers.rst.Parser,)
settings = docutils.frontend.OptionParser(
components=components).get_default_values()
document = docutils.utils.new_document('<rst-doc>', settings=settings)
parser.parse(text, document)
return document
class MyVisitor(docutils.nodes.NodeVisitor):
def visit_reference(self, node: docutils.nodes.reference) -> None:
"""Called for "reference" nodes."""
print(node)
def unknown_visit(self, node: docutils.nodes.Node) -> None:
"""Called for all other node types."""
print(node)
if __name__ == '__main__':
doc = parse_rst('spam spam lovely spam')
visitor = MyVisitor(doc)
doc.walk(visitor)
除非 reST 内容包含特定于 Sphinx 的指令/角色(例如.. glossary::
、:term:
等),否则该方法有效。所以我需要 Sphinx 解析器而不是 docutils 解析器。
我尝试了子类化sphinx.parsers.Parser
;使用from sphinx.application import Sphinx
thenapp.build()
来伪造一个 sphinx docs 项目。
但是参考和解决方法变得复杂,所以我怀疑我以错误的方式接近它。我可以在成熟的sphinx-build
工作流程之外使用 sphinx 解析器吗?
解决方案
推荐阅读
- vba - 如何在访问表单的选项卡控件中对 1 个字段使用 Dlookup
- java - 如何使用 notifyDataSetChanged() 刷新 RecyclerView
- c++ - 它->首先给出什么类型?
- sql - 如何将 Array[String] 输出到 Json 文件?
- ios - Xcode 非公共 API
- angular - 更新 Angular 8.0 后模块没有导出的成员组件
- django - Django Cassandra 引擎没有正确记录日期时间
- php - laravel nova 隐藏索引页面上的编辑按钮
- r - 向量长度不均匀的expand.grid问题
- laravel - 默认 laravel 通知 --> 数据不工作