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

2024-05-05

我有一些 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)很容易获得。请参阅我的回答这个问题 https://stackoverflow.com/q/10766609/623518有关提取部分已处理 XML 的示例。让我知道这是否是您想要的。无论如何,这里...

您可以使用 Docutils 非常轻松地操作 reStructuredText。首先,您可以使用 Docutils 发布 reStructuredText 的 Docutils 文档树 (doctree) 表示形式publish_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'

现在标记已经丢失。如果注释太花哨,可以很容易地在上面结果的第一行下插入一些破折号以返回到您的部分标题。我不确定对于更复杂的内联标记您需要做什么。希望以上内容对您来说是一个良好的起点。

Note: 查询时doctree.ids the ids我传递的属性与 reStructuredText 中的定义略有不同:前导下划线已被删除,所有其他下划线已被替换为-s。这就是 Docutils 标准化引用的方式。编写一个函数将 reStructuredText 引用转换为 Docutils 的内部表示非常简单。否则,我确信如果您深入研究 Docuitls,您可以找到执行此操作的例程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 :ref:? 从 ReST 文档中提取文本块 的相关文章

随机推荐