计算文件中非注释或非空白的行数

  • 本文关键字:空白 注释 文件 计算 python
  • 更新时间 :
  • 英文 :


我正在尝试使用以下代码计算SLOC的数量,但它不起作用,它只是打印0。有人能帮助吗

f = open("/content/drive/MyDrive/Rental.java", "r")
#print(f.read())
for l in f:
count=0
if (l.strip() and l.startswith('/')):
count += 1
print(count)

在每次迭代中重置count,因此只能得到01的答案。相反,将其设置在循环之前。

l.strip()不修改l。相反,它返回一个新字符串您应该将其分配给l

此外,您需要计算有多少行不是注释,因此需要检查not l.startswith('/')。检查.startswith('//')可能更有意义,因为在java中,一个正斜杠不会产生注释。事实上,如果你只做.startswith('/'):,这样的东西会被错误地识别为有注释行

double a = 1.0
/ 5.0;

这是你的固定代码:

count = 0
f = open("/content/drive/MyDrive/Rental.java", "r")
for l in f:
l = l.strip()
if l and not l.startswith('//'):
count += 1
print(count)

我忽略了使用/* ... */的多行注释的情况,因为您在最初的问题中还没有解决它。

您可以使用sum((函数直接获取计数:

with open("/content/drive/MyDrive/Rental.java", "r") as f:
SLOC = sum(not line.startswith('//') for line in map(str.strip,f) if line)
print(SLOC)

在线迭代器上使用map(str.strip,…(可以很容易地排除空行并检测缩进的注释

尝试在循环之前定义count

f = open("/content/drive/MyDrive/Rental.java", "r")
count = 0
#print(f.read())
for l in f:
if (l.strip() and l.startswith('/')):
count += 1
print(count)

最新更新