我有一些 reStructuredText 文档。我想在在线帮助中使用其中的片段。似乎一种方法是通过引用“剪掉”标记片段,例如
.. _my_boring_section:
Introductory prose
------------------
blah blah blah
.. _my_interesting_section:
About this dialog
-----------------
talk about stuff which is relevant in contextual help
如何使用 python/docutils/sphinx 提取 _my_interesting_section 标记的标记?
最佳答案
除了子类化和自定义 Docutils 解析器之外,我不确定如何执行此操作。如果您只需要 reStructuredText 的相关部分并且不介意丢失一些标记,那么您可以尝试使用以下内容。或者,特定部分的已处理标记(即转换为 HTML 或 LaTeX 的 reStructuredText)非常容易获得。请参阅我对 this question 的回答有关提取部分已处理 XML 的示例。让我知道这是否是您想要的。无论如何,这里是...
您可以使用 Docutils 非常轻松地操作 reStructuredText。首先,您可以使用 Docutils publish_doctree
函数发布 reStructuredText 的 Docutils 文档树 (doctree) 表示形式。可以轻松地遍历该文档树并搜索特定的文档元素,即具有特定属性的节。搜索特定部分引用的最简单方法是检查文档树本身的 ids 属性。 doctree.ids
只是一个字典,其中包含所有引用到文档适当部分的映射。
from docutils.core import publish_doctree
s = """.. _my_boring_section:
Introductory prose
------------------
blah blah blah
.. _my_interesting_section:
About this dialog
-----------------
talk about stuff which is relevant in contextual help
"""
# Parse the above string to a Docutils document tree:
doctree = publish_doctree(s)
# Get element in the document with the reference id `my-interesting-section`:
ids = 'my-interesting-section'
try:
section = doctree.ids[ids]
except KeyError:
# Do some exception handling here...
raise KeyError('No section with ids {0}'.format(ids))
# Can also make sure that the element we found was in fact a section:
import docutils.nodes
isinstance(section, docutils.nodes.section) # Should be True
# Finally, get section text
section.astext()
# This will print:
# u'About this dialog\n\ntalk about stuff which is relevant in contextual help'
现在标记已丢失。如果注释太花哨,可以很容易地在上面结果的第一行下插入一些破折号以返回到您的部分标题。我不确定对于更复杂的内联标记您需要做什么。希望以上内容对您来说是一个良好的起点。
注意:查询doctree.ids
时,我传递的ids
属性与reStructuredText中的定义略有不同:前导下划线有已删除,所有其他下划线已替换为 -
。这就是 Docutils 标准化引用的方式。编写一个函数将 reStructuredText 引用转换为 Docutils 的内部表示非常简单。否则,我确信如果您深入研究 Docuitls,您可以找到执行此操作的例程。
关于python - 通过 :ref:? 从 ReST 文档中提取文本 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8358522/