如何在python中获取字符串文字行号?

时间:2020-06-03 15:27:48

标签: python python-3.x python-2.7 abstract-syntax-tree

我有一个可以在类,函数和方法中找到所有文档字符串的函数,但是我目前正在努力寻找一种解决方案来获取所有这三个选项中都不存在的所有文档字符串。有没有一种方法可以使用ast(或任何其他方法)来获取宽松的文档字符串的行号?

示例文件,我将检查以找到所有文档字符串行号-

a = '\ttesting this file!'
b = "abc"
print a

def trigger():
    a = b'\r\n'
    b = "\t"


"""                     <---- I want these line numbers
dasdas                  <---- I want these line numbers
adasdsa                 <---- I want these line numbers
"""                     <---- I want these line numbers

class A:
    """                       Function correctly picks up all docstring lines below
    dsadasd
    dsadas
    """
    def new():
        """
        dsadas
        :return:

这是我当前的功能-

 def get_all_docstring_positions(self, file):
        """
        this method will return all docstring positions in functions, classes & methods.

        :param file: file to iterate through
        :return: list of positions
        """
        lines_to_skip = []

        os.getcwd(), os.listdir(os.getcwd())
        root = ast.parse(open(file).read())

        # Functions
        for node in ast.walk(root):
            if isinstance(node, ast.FunctionDef):
                if self.node_status(node):
                    lines_to_skip.append(list(range(node.lineno + 1, node.body[0].value.lineno + 1)))
            elif isinstance(node, ast.ClassDef):
                # Classes
                if self.node_status(node):
                    lines_to_skip.append(list(range(node.lineno + 1, node.body[0].value.lineno + 1)))
                for class_ in node.body:
                    if isinstance(class_, ast.FunctionDef):
                        for n in class_.body:
                            # Methods
                            if isinstance(n, ast.FunctionDef):
                                if self.node_status(n):
                                    lines_to_skip.append(list(range(n.lineno + 1, n.body[0].value.lineno + 1)))

        # SORTING ONLY FOR UNIT TESTING, THIS SORT WILL NOT BE NEEDED
        return sorted(list(itertools.chain.from_iterable(lines_to_skip)))

    def node_status(self, node):
        """
        reduced duplication

        :param node: node to check against
        :return: boolean
        """
        if node.body and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Str):
            return True
        return False

对于上面的示例文件,get_all_docstring_positions将返回[15, 16, 17, 18, 20, 21, 22, 23]

任何帮助将不胜感激。

0 个答案:

没有答案
相关问题