如何解析numpydoc文档字符串并访问组件? [英] How can I parse a numpydoc docstring and access components?

查看:117
本文介绍了如何解析numpydoc文档字符串并访问组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个numpydoc文档字符串,并以编程方式访问每个组件.

I'd like to parse a numpydoc docstring and access each component programatically.

例如:

def foobar(a, b):
   '''Something something

   Parameters
   ----------
   a : int, default: 5
        Does something cool
   b : str
        Wow
'''

我想做的是:

parsed = magic_parser(foobar)
parsed.text  # Something something
parsed.a.text  # Does something cool
parsed.a.type  # int
parsed.a.default  # 5

我一直在搜索,发现了 numpydoc

I've been searching around and found things like numpydoc and napoleon but I haven't found any good leads for how to use them in my own program. I'd appreciate any help.

推荐答案

您可以使用numpydoc中的NumpyDocString将文档字符串解析为Python友好的结构.

You can use NumpyDocString from numpydoc to parse docstrings into a Python-friendly structure.

这是如何使用它的示例:

This is an example of how to use it:

from numpydoc.docscrape import NumpyDocString


class Photo():
    """
    Array with associated photographic information.


    Parameters
    ----------
    x : type
        Description of parameter `x`.
    y
        Description of parameter `y` (with type not specified)

    Attributes
    ----------
    exposure : float
        Exposure in seconds.

    Methods
    -------
    colorspace(c='rgb')
        Represent the photo in the given colorspace.
    gamma(n=1.0)
        Change the photo's gamma exposure.

    """

    def __init__(x, y):
        print("Snap!")

doc = NumpyDocString(Photo.__doc__)
print(doc["Summary"])
print(doc["Parameters"])
print(doc["Attributes"])
print(doc["Methods"])

但是,由于我不了解的原因,这不适用于您给出的示例(也没有很多我想在其上运行的代码).相反,您需要根据用例使用特定的FunctionDocClassDoc类.

However, this won't work with the example you gave (nor a lot of the code I want to run this on) for reasons I don't understand. Instead, you need to use the specific FunctionDoc or ClassDoc class, depending on your use-case.

from numpydoc.docscrape import FunctionDoc

def foobar(a, b):
   """
   Something something

   Parameters
   ----------
   a : int, default: 5
        Does something cool
   b : str
        Wow
   """

doc = FunctionDoc(foobar)
print(doc["Parameters"])

我通过查看此测试他们的源代码.因此,这并没有真正记录在案,但希望足以让您入门.

I figured this all out by looking at this test in their source code. So, this isn't really documented, but hopefully is enough for you to get started.

这篇关于如何解析numpydoc文档字符串并访问组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆