1. 题目
第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
2. 思路
- 首先需要遍历目录,挑选出以
.py
结尾的文件 - 空行可以匹配行末尾的
\n
- 注释需要匹配起始为
#
或者为若干空格#
的情况, 多行注释要与多行字符串相区分,本例中暂不考虑
3. 实现
# -*- coding: utf-8 -*-
import os
import os.path
import re
def count_code_lines(path):
if path is None:
return
count_code = 0
count_null = 0
count_comment = 0
files = [os.path.join(path, x) for x in os.listdir(path) if os.path.splitext(x)[1] == ".py"]
for file in files:
with open(file, encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line)
count_code += 1
if len(line) == line.count("\n"):
count_null += 1
if len(re.findall(r"^\s*#", line)) > 0:
count_comment += 1
if lines[-1][-1:] == "\n":
count_null += 1
print("BLANK: %s" % count_null)
print("COMMENT: %s" % count_comment)
print("CODE: %s" % (count_code - count_null - count_comment))
if __name__ == "__main__":
count_code_lines(".")
网友评论