【问题标题】:Extract multiple variable names in docstrings在文档字符串中提取多个变量名
【发布时间】:2021-03-22 14:32:36
【问题描述】:

我正在尝试从 Python 的文档字符串中查找所有变量名。例如,文档字符串的格式如下:

Scans through a string for substrings matched some patterns (first-subgroups only).

Args:
    text: A string to be scanned.
    patterns: Arbitrary number of regex patterns.

Returns:
    When only one pattern is given, returns a string (None if no match found).
    When more than one pattern are given, returns a list of strings ([] if no match found).

我想用正则表达式同时提取textpatterns

由于这个特殊的正则表达式,我尝试使用此代码查找以: 结尾的断行后的所有元素:

string = """Args:
    text: A string to be scanned.
    patterns: Arbitrary number of regex patterns."""
print(re.findall('Args:[\r\n]+(.+?):', string))

但是这个正则表达式没有捕获任何内容,我做错了什么?

【问题讨论】:

    标签: python docstring


    【解决方案1】:

    我会使用docstring-parser 而不是重新发明轮子。它支持 Google、ReST 和 Numpydoc 样式的文档字符串。

    from docstring_parser import parse
    
    s = """
    Scans through a string for substrings matched some patterns (first-subgroups only).
    
    Args:
        text: A string to be scanned.
        patterns: Arbitrary number of regex patterns.
    
    Returns:
        When only one pattern is given, returns a string (None if no match found).
        When more than one pattern are given, returns a list of strings ([] if no match found).
    """
    doc_str = parse(s)
    print([param.arg_name for param in doc_str.params])
    

    输出

    ['text', 'patterns']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-10
      • 2013-01-14
      • 2012-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2011-12-07
      • 1970-01-01
      相关资源
      最近更新 更多