Extract field list from reStructuredText

前端 未结 3 1352
北海茫月
北海茫月 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:53

    I have an alternative solution that I find to be less of a burden, but maybe more brittle. After reviewing the implementation of the node class https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/nodes.py you will see that it supports a walk method that can be used to pull out the wanted data without having to create two different xml representations of your data. Here is what I am using now, in my protoype code:

    https://github.com/h4ck3rm1k3/gcc-introspector/blob/master/peewee_adaptor.py#L33

    from docutils.core import publish_doctree
    import docutils.nodes
    

    and then

    def walk_docstring(prop):
        doc = prop.__doc__
        doctree = publish_doctree(doc)
        class Walker:
            def __init__(self, doc):
                self.document = doc
                self.fields = {}
            def dispatch_visit(self,x):
                if isinstance(x, docutils.nodes.field):
                    field_name = x.children[0].rawsource
                    field_value = x.children[1].rawsource
                    self.fields[field_name]=field_value
        w = Walker(doctree)
        doctree.walk(w)
        # the collected fields I wanted
        pprint.pprint(w.fields)
    

提交回复
热议问题