这是我的代码,用于计算空白行,源代码行以及总行数和注释行。我用来检查一行中是否有'//'来检查它是否是注释行,但我知道它是错误的。因为'/.../'可以形成评论块。如何计算注释块中的行数?
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;
答案 0 :(得分: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
条件可以简化,但我认为你可以让它发挥作用。