This is my code to count blank lines ,source code lines and total lines and comment lines. I use to check if there is '//' in a line to check if it is a comment line but I know it is wrong. Because '/ ... /' can form a comment block. How to count the number of lines in a comment block?
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;
There are problems with your code eg you can't just remove all whitespaces (you might consider /{whitespace}/
a comment). I'm not gonna provide actual code but this should give you a rough idea.
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
The conditions could be simplified, but I think you can get it to work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.