首页 > 代码库 > 代码注释率统计的Python及Java实现

代码注释率统计的Python及Java实现

 

这是一个简单的Java代码注释率统计工具,能够查找某个指定目录下的每个.java文件注释率及该路径下所有.java文件的总注释率。

注释率=注释代码行数/代码总行数,其中代码总行数包括注释行和空格行。

在Java中有行注释(//)、块注释(/*……*/)和Javadoc注释(/**……*/)三种风格,通过逐行读取文件,并判断是否包换这些字符就可以实现判断一行代码是否包含注释。为了增加准确率,引号内的字符串不计入统计范围。

Python的实现如下:

#coding:utf8 
#@author lyonwang
import os 

totalCodeCount = 0    #代码总行数(包括注释及空格)
totalCommentCount = 0    #注释行数

def readFilePath(path):
    global totalCodeCount 
    global totalCommentCount 
    fileList = []
    files = os.listdir(path)    #打开指定路径下所有文件及文件夹
    for f in files:
        if(os.path.isfile(path + \\ + f) and (f[f.rfind(.):]==.java)):    #获取.java文件
            ff=open(path + \\ +f)
            codeCount = 0
            commentCount = 0
            flag = False    #块注释标识
            while True:
                line = ff.readline()    #逐行读取.java文件    
                if len(line) == 0: 
                    break
                sLine = ‘‘
                ss = line.split(\")
                for i in range(0,len(ss)):
                    if i%2!=0:
                        ss[i]=@
                    sLine = sLine + ss[i]
                if sLine.find(//)>=0:        
                    commentCount=commentCount+1
                elif sLine.find(/*)>=0:    #块注释
                    commentCount=commentCount+1
                    flag = True
                if sLine.find(*/)>=0:
                    flag = False
                if flag :
                    if sLine.find(*)>=0:
                        commentCount=commentCount+1
                codeCount=codeCount+1
            print File Name:,f
            print Code Count:,codeCount
            print Comment Count:,commentCount
            print Annotation Rate:,commentCount*100/codeCount,"%"
            totalCodeCount = totalCodeCount+codeCount;
            totalCommentCount = totalCommentCount+commentCount;
        if(os.path.isdir(path + \\ + f)):        #文件夹则递归查找
            if(f[0] == .):  
                        pass  
                    else: 
                readFilePath(path + \\ + f)

filePath = raw_input(Project Path:)    #输入路径
readFilePath(filePath)
print *************
print Total Code Count:,totalCodeCount
print Total Comment Count:,totalCommentCount
print Total Annotation Rate:,totalCommentCount*100/totalCodeCount,"%"

Java实现链接:

王敏慎的Evernote共享笔记