【问题标题】:Extracting blocks of text from ReST documents by :ref:?通过 :ref:? 从 ReST 文档中提取文本块
【发布时间】:2011-12-02 15:22:02
【问题描述】:

我有一些 reStructuredText 文档。我想在在线帮助中使用它的 sn-ps。似乎一种方法是通过引用“剪掉”标记片段,例如

.. _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 标记的标记?

【问题讨论】:

    标签: python python-sphinx restructuredtext docutils


    【解决方案1】:

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

    您可以使用 Docutils 非常轻松地操作 reStructuredText。首先,您可以使用 Docutils publish_doctree 函数发布 reStructuredText 的 Docutils 文档树 (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 = 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中的定义略有不同:前导下划线已被删除,所有其他下划线已被@987654328替换@s。这就是 Docutils 规范化引用的方式。编写一个函数来将 reStructuredText 引用转换为 Docutils 的内部表示非常简单。否则,我敢肯定,如果您仔细研究 Docuitls,您可以找到执行此操作的例程。

    【讨论】:

    • 这真是太棒了。感谢您的回答。代码中只有一种类型section = document.ids[ids] 应该是section = doctree.ids[ids]
    • @Premkumarchalmeti 好地方,谢谢!我已经更新了代码。
    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2015-11-04
    • 1970-01-01
    相关资源
    最近更新 更多