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 == "\n":
                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)

转载于:https://www.cnblogs.com/Mysterious/p/7482432.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值