从ReST文档中提取文本块:ref:?

时间:2011-12-02 15:22:03

标签: python python-sphinx restructuredtext docutils

我有一些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标记的标记?

1 个答案:

答案 0 :(得分:1)

除了子类化和自定义Docutils解析器之外,我不确定如何做到这一点。如果您只需要reStructuredText的相关部分并且不介意丢失一些标记,那么您可以尝试使用以下内容。或者,很容易获得特定部分的已处理标记(即reStructuredText转换为HTML或LaTeX)。有关提取已处理XML的一部分的示例,请参阅我对this question的回答。如果这是你想要的,请告诉我。无论如何,这里... ...

您可以使用Docutils轻松操作reStructuredText。首先,您可以使用Docutils publish_doctree函数发布reStructuredText的Docutils文档树(doctree)表示。可以容易地遍历该doctree并搜索具有特定属性的特定文档元素,即部分。搜索特定节引用的最简单方法是检查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 = document.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挖掘,你可以找到执行此操作的例程。