【问题标题】:Extract docstring form a python file using grep or awk使用 grep 或 awk 从 python 文件中提取文档字符串
【发布时间】:2018-04-08 21:41:03
【问题描述】:

我想使用 grep 或 awk 从我的 python 文件中提取所有文档字符串。 我试过了

cat test.py | grep """[\w\W]*?"""

但我没有看到任何输出。 说测试test.py 看起来像这样。

import libraries

class MyClass(object):
    """Docstring to this class. 
       second line of docstring."""

    def myClassMethod(a,b):
        """Docstring of the method. 
           another line in docstring of the method."""
        return a + b

那么输出应该是用三引号括起来的所有内容。

"""Docstring to this class. 
second line of docstring."""
"""Docstring of the method. 
another line in docstring of the method."""

【问题讨论】:

  • 我们需要更多细节,例如输入样本和预期输出。
  • 我添加了测试用例并修正了错别字。

标签: python regex awk grep


【解决方案1】:

从 Python 代码中提取文档字符串的正确方法是通过实际的 Python 解析器(ast 模块):

#!/usr/bin/env python
import ast

with open('/path/to/file') as f:
    code = ast.parse(f.read())

for node in ast.walk(code):
    if isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.Module)):
        docstring = ast.get_docstring(node)
        if docstring:
            print(repr(docstring))

在您的示例上运行将输出:

'Docstring to this class. \nsecond line of docstring.'
'Docstring of the method. \nanother line in docstring of the method.'

只是为了好玩,我们也可以使用 GNU awk:

$ awk -v RS= -v FPAT="'''.*'''|"'""".*"""' '{print $1}' file
"""Docstring to this class. 
       second line of docstring."""
"""Docstring of the method. 
           another line in docstring of the method."""

【讨论】:

  • 我找到了这个方法,但我想知道这是否可以使用 grep 或 awk 完成
  • 我不推荐它超过 Python 版本,但看看我刚刚添加的 awk 方法。
  • 非常感谢这满足了我的好奇心
【解决方案2】:

使用 P(perl) grep 您可以执行以下操作:

grep -Poz '"""[^"]+"""' test.py

输出:

"""Docstring to this class. 
       second line of docstring.""""""Docstring of the method. 
           another line in docstring of the method."""

【讨论】:

  • 我收到一个错误grep: unescaped ^ or $ not supported with -Pz
  • 我的是grep (GNU grep) 2.24,如果我们使用除 perl 正则表达式之外的其他东西,它是否可以工作。
猜你喜欢
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多