如何计算Java文件中的注释行?
这是我用来计算Java文件中不同代码行数量的一部分代码。在大多数情况下,这段代码能正确计算行数。但是如果注释的格式是这样的:
/* .......
*.......
*/
那么它会把这个注释块只算作两行。
for eachLine in allLines:
if eachLine != " " :
eachLine = eachLine.replace(" ",""); #remove space
eachLine = self.trim(eachLine); #remove tabIndent
if (iscomment==False):
if(eachLine.strip().startswith("//")): #LINECOMMENT
commentCount += 1;
if eachLine == "":
blankCount += 1;
if(eachLine.strip().startswith("/*")):
commentCount += 1;
if(not eachLine.strip().endswith("*/")):
iscomment=True
else :
commentCount += 1;
if(eachLine.find("*/")):
iscomment=False
lineCount = lineCount + 1;
codeCount=lineCount-commentCount-blankCount
2 个回答
0
1
你可以考虑使用正则表达式:
import re
comments = re.findall('#.*?\n', allLines)
for item in re.findall('/\*.?*\*/', allLines):
for row in item.split('\n'):
comments.append(row)
print(len(comments))
大概是这样的,我在一个很简单的项目上试过,结果能正确获取到需要的行数。