Python实现代码统计(代码+注释+空

发布时间:2019-09-08 09:12:35编辑:auto阅读(1617)

    # -*- coding: utf-8 -*-
    """
    Created on Thu Apr 17 17:15:40 2014
    @author: author
    """
    import os;
    path_head = '代码路径头部'
    path_list = '代码绝对路径' 
    fileClasses = ['java']   #需要统计的文件类型
    totalLines = 0
    commentAll = 0
    normalAll = 0
    whiteAll = 0
    for root,dirs,files in os.walk(path_head + path_list):
        #处理路径中的 '/'
        dirLen = len(root)
        lastChar = root[dirLen-1:dirLen]
        if lastChar =='/' :
            root = root[0:dirLen-1]
             
        for afile in files:
            fileDir = root+'/'+ afile
                 
            #过滤文件类型
            strs = afile.split('.')
            fileClass = strs[len(strs)-1]
            if fileClass not in fileClasses :
                continue
                 
            with open(fileDir) as file:
                commentLines = 0
                whiteLines = 0
                normal = 0
                comment = False
                     
                lines = file.readlines()
                for i in lines:
                    i = i.strip()
                    #空行
                    if(i==''):
                        whiteLines=whiteLines+1
                    #注释 /*   */
                    elif(i.startswith('/*') and True==i.endswith('*/')):
                        commentLines=commentLines+1
                    #注释 /* 开头
                    elif(i.startswith('/*') and False==i.endswith('*/')):
                        commentLines=commentLines+1
                        comment=True
                    #注释 中间 和 */ 结尾
                    elif(True==comment):
                        commentLines=commentLines+1
                        if(i.endswith('*/')):
                            comment=False
                    #注释 //
                    elif(i.startswith('//')):
                        commentLines=commentLines+1
                    #代码
                    else:
                        normal=normal+1
                #单文件统计结果
                print ('%s 代码行数:%d 空行数:%d 注释行数:%d'%(fileDir[len(path_head):], normal, whiteLines, commentLines))
                commentAll+= commentLines
                normalAll += normal
                whiteAll += whiteLines
    #统计结果
    print ('总行数:%d' %(commentAll + normalAll + whiteAll))
    print ('总代码行数:%d' %(normalAll))
    print ('总注释行数:%d' %(commentAll))
    print ('总空行数:%d' %(whiteAll))

    参考网上的代码修改而成,没有什么技术含量。

关键字