如题:
有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
提示说需要用到 enumerate 和 defaultdict ,个人觉得用到os就足够了, 而且很简单, 开始准备用正则匹配,
后来发现, 为什么要这么麻烦, 一边读取文件一边统计,文件读取完毕也就统计完了(好吧, 主要是因为这部分正则不太好写)
__author__ = 'Administrator'
# coding=utf-8
import os
rootDir = "d:/code/"
class Code():
"""第 0007 题:'
有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。"""
def __init__(self):
return
notes_line = 0
code_line = 0
blank_line = 0
def count_code(self, path=rootDir):
for root, dirs, files in os.walk(path):
for filename in files:
#判断文件后缀
if filename[filename.find(".")+1:] == 'py':
self.each_file(filename)
print("code lines:", self.code_line)
print("notes lines:", self.notes_line)
print("blank lines:", self.blank_line)
def each_file(self, filename):
with open(rootDir + filename) as handle:
for line in handle:
line = line.strip()
if len(line) == 0:
self.blank_line += 1
elif line[0] == "#":
self.notes_line += 1
else:
self.code_line += 1
if __name__ == '__main__':
Code().count_code()
运行结果: