python - 使用 grep 或 awk 从 python 文件中提取文档字符串

标签 python regex awk grep

我想使用 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 代码中提取文档字符串的正确方法是通过实际的 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."""

关于python - 使用 grep 或 awk 从 python 文件中提取文档字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46972403/

相关文章:

PHP 正则表达式匹配包含符号的有效薪水

Python:鼠标按下时计数,鼠标向上时停止

python - 如何在 django 查询中排序?

python - 如何使用 setuptools 安装 scipy 和 numpy

python - 清除 HTML 中的非正文文本

javascript - 在 Javascript 中使用正则表达式解析 XHTML 字符串并将其转换为 DOM

linux - 比较两个文件并获取Linux中第三个文件的位置

bash - bash : how to stop new line being added? 中的 awk 命令

python - 使用 bash 或 python 将路由器配置文件转换为 csv

python - cross_val_score 和估计器分数之间的区别?