如何使用Python计算java源代码中的注释行?

2024-07-04 17:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我用来计算空行数、源代码行数、总行数和注释行数的代码。我经常检查一行中是否有“//”,以检查它是否是一个注释行,但我知道它是错误的。因为。。。/'可以形成注释块。如何计算注释块中的行数?在

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;

Tags: pathselfifosextensionfilenamefileprint
1条回答
网友
1楼 · 发布于 2024-07-04 17:09:44

您的代码有一些问题,例如,您不能只删除所有空白(您可以考虑/{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

条件可以简化,但我想你可以让它发挥作用。在

相关问题 更多 >

    热门问题