import os

# 获取文件下的所有py文件,返回py文件列表
import re


def getPyFilesInDir(dirpath):
    # 拿到当前路径下的(一级)文件(含文件夹)列表
    flist = os.listdir(dirpath)
    pyFileList = []  # 建立Py文件列表

    # 遍历一级子路径
    for name in flist:

        # 获得文件的完整路径
        filepath = dirpath + "/" + name

        # 是文件且是Py文件
        if os.path.isfile(filepath) and name.endswith(".py"):
            pyFileList.append(filepath)

        # 不是Py文件
        elif os.path.isfile(filepath) and not name.endswith(".py"):
            print("%s不是py源代码文件" % (name))
            pass

        # 是文件夹
        elif os.path.isdir(filepath):
            # print("继续做同样的事情")

            # 递归遍历(自己调自身,终止条件为路径没有文件夹),兼并子文件夹的结果
            pyFileList += getPyFilesInDir(filepath)

        else:
            print("wtf")

    return pyFileList


# 以醒目格式打印列表
def printListClearly(mlist):
    print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
    for path in mlist:
        print(path)
    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")


# 分析单个文件的代码量
def analyzeCodeFile(path):
    # 预定义结果
    totalLines = 0
    commentLines = 0
    blankLines = 0
    effectiveLines = 0
    # 标记当前行是否处于多行注释的内部
    betweenMultipleComment = False
    try:
        file = open(path, "r", encoding="utf-8")
        lineList = file.readlines()
        totalLines = len(lineList)

        for line in lineList:
            # 空行
            if line == "\n":
                blankLines += 1

            # 判断自结束的多行注释
            elif re.match("^\s*'''.*'''\s*$", line):
                print("%s劳资是自结束多行注释结尾" % (line))
                commentLines += 1
                betweenMultipleComment = False

            # 判断多行注释开头
            elif re.match(r"^\s*'''", line) != None and betweenMultipleComment == False:
                betweenMultipleComment = True
                commentLines += 1
                print("%s劳资是多行注释开头" % (line))

            # 判断多行注释结尾
            elif re.match(r".*'''\s*$", line) != None and betweenMultipleComment == True:
                betweenMultipleComment = False
                commentLines += 1
                print("%s劳资是多行注释结尾" % (line))

            # 多行注释内部
            elif betweenMultipleComment:
                commentLines += 1
                print("%s劳资是多行注释内容" % (line))

            # 单行注释
            elif betweenMultipleComment == False and re.match(r"^\s*#", line) != None:
                commentLines += 1
                print("%s劳资是单行注释" % (line))

            else:
                print("%s劳资是单行代码" % (line))
                effectiveLines += 1
                pass

        # effectiveLines = totalLines - blankLines - commentLines

        print("在文件%s中:" % (path))
        print("totalLines=", totalLines)
        print("commentLines=", commentLines)
        print("blankLines=", blankLines)
        print("effectiveLines=", effectiveLines)

        if effectiveLines < commentLines:
            print("\n\n\n\n\n可疑对象\n\n\n\n\n", path)
        file.close()

        return {"totalLines": totalLines, "commentLines": commentLines, "blankLines": blankLines,
                "effectiveLines": effectiveLines}

    # 捕获并处理乱码异常
    except UnicodeDecodeError:
        print("读取%s发生编码错误" % (path))
        pass


def run():
    FILE_PATH = r"D:\PycharmProjects\demos\W3"
    # 遍历文件夹,拿出所有的py文件,返回一个py文件列表
    pyFileList = getPyFilesInDir(FILE_PATH)
    printListClearly(pyFileList)
    # 预定义结果
    totalLines = 0
    commentLines = 0
    blankLines = 0
    effectiveLines = 0
    # 遍历所有的py文件,逐个统计代码量
    for path in pyFileList:
        resdict = analyzeCodeFile(path)
        totalLines += resdict["totalLines"]
        commentLines += resdict["commentLines"]
        blankLines += resdict["blankLines"]
        effectiveLines += resdict["effectiveLines"]
        pass

    # 打印结果
    print("==================================================")
    print("在文件夹%s中:" % (FILE_PATH))
    print("总代码量:%d" % (totalLines))
    print("总注释量:%d,占比%.2f%%" % (commentLines, commentLines * 100 / totalLines))
    print("总空行数:%d,占比%.2f%%" % (blankLines, blankLines * 100 / totalLines))
    print("有效代码:", effectiveLines)
    print("==================================================")


if __name__ == '__main__':
    run()
    # analyzeCodeFile(r"D:\python1701\demos\W2\day2\PersonIII.py")
    pass

results matching ""

    No results matching ""