Python函数名称查找程序无法正常工作

时间:2016-12-12 23:50:02

标签: python

尝试创建一个函数来查找文件中python函数的名称 对于python类我不知道为什么它只返回我在函数名称之间添加的逗号

def pythonanalysis(s):
    pythonlen = str(s.count("\n"))
    functionname = ''
    funcdoc = s
    counter = 0
    while funcdoc.find("def") != -1:
        function = funcdoc.find("def")
        funcdoc = funcdoc[function + 4:funcdoc.find("(")]
        functionname += funcdoc[:funcdoc.find("(")] + ", "
        counter += 1
        print(functionname)
    forlen = str(s.count("for"))
    iflen = str(s.count("if"))
    whilelen = str(s.count("while"))
    authnum = s.find('__author__ =')
    author = s[authnum + 14:]
    authname = author[:author.find('\'')]

    return "There are " + pythonlen + " lines in this file \n\
    There are "+ str(counter) + " functions in this document named: " + functionname + "\n\
    There are " + forlen+" for loops and " + iflen + " if loops and " + whilelen + " while loops\n\
    The author is " + authname

1 个答案:

答案 0 :(得分:1)

    function = funcdoc.find("def")
    funcdoc = funcdoc[function + 4:funcdoc.find("(")]

你发现的“(”很可能是在“def”之前,这会在这里产生一个空字符串!即使你确实找到了“(”就在函数名之后,你也放弃了整个该点之后的文件,因此您永远找不到多个函数。提示:str.find()方法采用可选的第二个参数来指定搜索的起始点。