2014-03-25 49 views
0

這是我的代碼來計算空白行,源代碼行和總行以及註釋行。我用來檢查一行中是否有'//'來檢查它是否是註釋行,但我知道它是錯誤的。因爲'/ ... /'可以形成註釋塊。如何計算註釋塊中的行數?如何使用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; 
+0

我只記得,即使'/'。該行可能不是註釋行,因爲它可能在正常語句之後。現在我更困惑了。 – deathlee

+0

所以你正在尋找包含純評論和無代碼的行? – atoMerz

+0

是的,這就是我的意思 – deathlee

回答

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 

條件可以簡化,但我認爲你可以得到它的工作。

相關問題