這是一個簡單的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實現鏈接: