簡體   English   中英

如何使用Python計算Java源代碼中的注釋行?

[英]How to use Python to count comment line in a java source code?

這是我的代碼,用於計算空白行,源代碼行以及總計行和注釋行。 我經常檢查一行中是否有“ //”,以檢查它是否為注釋行,但我知道這是錯誤的。 因為“ / ... /”可以形成注釋塊。 如何計算注釋塊中的行數?

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;

您的代碼存在問題,例如您不能僅刪除所有空格(您可能考慮使用/{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

條件可以簡化,但是我認為您可以使它起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM