如何使用Python统计Java源代码中的注释行?
这是我用来统计空行、源代码行、总行数和注释行的代码。我用来检查一行是否是注释行的方法是看里面有没有'//',但我知道这样做不太对。因为'/*...*/'也可以形成一个注释块。那么,怎么才能统计注释块里的行数呢?
def FileLineCount(self,filename):
(filepath,tempfilename) = os.path.split(filename);
(shotname,extension) = os.path.splitext(tempfilename);
if extension == '.java' : # file type
file = open(filename);
self.sourceFileCount += 1;
allLines = file.readlines();
file.close();
lineCount = 0;
commentCount = 0;
blankCount = 0;
codeCount = 0;
for eachLine in allLines:
if eachLine != " " :
eachLine = eachLine.replace(" ",""); #remove space #remove tabIndent
if eachLine.find('//') == 0 : #LINECOMMENT
commentCount += 1;
else :
if eachLine == "":
blankCount += 1;
else :
codeCount += 1;
lineCount = lineCount + 1;
self.all += lineCount;
self.allComment += commentCount;
self.allBlank += blankCount;
self.allSource += codeCount;
print filename;
print ' Total :',lineCount ;
print ' Comment :',commentCount;
print ' Blank :',blankCount;
print ' Source :',codeCount;
1 个回答
1
你的代码有一些问题,比如你不能随便去掉所有的空格(因为你可能会把/{whitespace}/
当成注释)。我不会给你具体的代码,但这应该能让你大致明白。
for each line of code
1. Remove all white space from the beginning (left trimming).
2. If mode is not multi-line and the line contains `//` increment counter.
3. else if mode is not multi-line and the line contains `/*` go to multi-line mode.
4. else if mode is multi-line
increment coutner
if line contains `*/` exit multi-line mode
条件可以简化一下,不过我觉得你应该能让它正常工作。