• python3 计算文件夹中所有py文件里面代码行数,注释行数,空行数


    import os,re
    
    #代码所在位置
    FILE_PATH = './'
    
    def analyze_code(codefilesource):
        '''
        打开一个py文件统计其中的代码行数,包括空格和注释
        返回该文件总行数,注释函数,空行输
        :param codefilesource:
        :return:
        '''
        total_line = 0
        comment_line = 0
        black_line = 0
        with open(codefilesource,'r', encoding='UTF-8') as f:
        # with open(codefilesource,'rb') as f:
            lines = f.readlines()
            total_line = len(lines)
            line_Index = 0
            #遍历每一行
            while line_Index < total_line:
                line = lines[line_Index]
                # line = str(line, encoding="utf-8")
                #检查是否为注释
                if line.startswith("#"):
                    comment_line += 1
                elif re.match("s*'''",line) is not None:
                    print("有s*")
                    print("line_Index:", line_Index)
                    while re.match(".*'''$",line) is None:
                        print(line)
                        print("line_Index:", line_Index)
                        line = lines[line_Index]
                        # line = str(line, encoding="utf-8")
                        comment_line += 1
                        if(line_Index < total_line):
                            line_Index += 1
    
                #检查是否为空行
                elif line == "
    ":
                    black_line += 1
                line_Index += 1
        print("在%s中"%codefilesource)
        print("代码行数:",total_line)
        print("注释行数:",comment_line,"占%0.2f%%"%(comment_line*100.0/total_line))
        print("空行数:", black_line, "占%0.2f%%" % (black_line * 100.0 / total_line))
        return [total_line,comment_line,black_line]
    
    def run(FILE_PATH):
        #切换到code所在目录
        os.chdir(FILE_PATH)
        #遍历所有py文件
        total_lines = 0
        total_comment_lines = 0
        total_black_lines = 0
        for i in os.listdir(os.getcwd()):
            if os.path.splitext(i)[1] == ".py":
                print(os.path.splitext(i))
                line = analyze_code(i)
                total_lines,total_comment_lines,total_black_lines = total_lines + line[0],total_comment_lines + line[1],total_black_lines+line[2]
        print("总代码行数:", total_lines)
        print("总注释行数:", total_comment_lines, "占%0.2f%%" % (total_comment_lines * 100.0 / total_lines))
        print("总空行数:", total_black_lines, "占%0.2f%%" % (total_black_lines * 100.0 / total_lines))
    if __name__ == '__main__':
        # analyze_code("calcTimes.py")
        # analyze_code("Demo.py")
        # analyze_code("file.py")
        run(FILE_PATH)
    
    
  • 相关阅读:
    经典多线程问题(四)-轮流打印字母和数字
    经典多线程问题 (一)-多线程售票
    买卖股票的最佳时机 II
    最长递增(严格递增)子序列-可以不连续
    环形链表 II
    最小栈
    买卖股票的最佳时机
    二叉树的层序遍历
    字符串相加
    最大子序和
  • 原文地址:https://www.cnblogs.com/Mysterious/p/7482432.html
Copyright © 2020-2023  润新知