Extract field list from reStructuredText

前端 未结 3 1354
北海茫月
北海茫月 2021-01-05 10:56

Say I have the following reST input:

Some text ...

:foo: bar

Some text ...

What I would like to end up with is a dict like this:

3条回答
  •  广开言路
    2021-01-05 11:57

    Here's my ElementTree implementation:

    from docutils.core import publish_doctree
    from xml.etree.ElementTree import fromstring
    
    source = """Some text ...
    
    :foo: bar
    
    Some text ...
    """
    
    
    def gen_fields(source):
        dom = publish_doctree(source).asdom()
        tree = fromstring(dom.toxml())
    
        for field in tree.iter(tag='field'):
            name = next(field.iter(tag='field_name'))
            body = next(field.iter(tag='field_body'))
            yield {name.text: ''.join(body.itertext())}
    

    Usage

    >>> next(gen_fields(source))
    {'foo': 'bar'}
    

提交回复
热议问题