0%

Python练习册:0007

题目

    有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。

分析

首先遍历文件夹内容,之前已经做过好多了,接着对空行(’\n’),注释(‘#’,‘’‘多行注释’‘’ / “”“多行注释”“”),代码(剩下的内容)分别计数即可。这里用到字符串的一些内置函数。值得注意的是如何统计多行注释,这里我用的是设置一个开关,遇到第一个注释符作为开始,第二个注释符作为结束,中间的内容全算注释。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
"""

import os

def count_lines(code_dir):
code_lines = 0
blank_lines = 0
comment_lines = 0
comment = False
for file in os.listdir(code_dir):
filename = os.path.join(code_dir,file)
with open(filename,"r") as f:
text = f.readlines()

for line in text:
#排除左边空格的干扰
line = line.lstrip(' ')

#单行注释
if(line.startswith('#')):
comment_lines += 1

#这里设置一个comment 作为开关
elif(line.startswith("'''") or line.startswith('"""')):
comment_lines += 1
comment = not comment

#“”“内的换行也算作注释”“”
elif(line.startswith('\n')):
if comment:
comment_lines += 1
else:
blank_lines += 1

#非注释内的内容算作代码
else:
if comment:
comment_lines += 1
else:
code_lines +=1

total = code_lines + blank_lines + comment_lines
print("共有代码:{}行".format(total))
print("代码:{}行".format(code_lines))
print("注释:{}行".format(comment_lines))
print("空行:{}行".format(blank_lines))

if __name__ == '__main__':
code_dir = 'code'
count_lines(code_dir)

参考

欢迎关注我的其它发布渠道