1 # -*-coding:utf-8-*-
2 __author__ = 'Deen'
3 '''
4 题目描述:
5 有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
6
7 根据注释和正常语句的区别,进行筛选计数
8 '''
9
10 import os
11
12
13 # 首先还是获取该目录下所有文件名,返回一个list进行储存
14 def list_files(dir, wirldcard, recursion):
15 files_text = list()
16 exts = wirldcard.split(" ")
17 files = os.listdir(dir)
18 for name in files:
19 fullname = os.path.join(dir, name)
20 if (os.path.isdir(fullname) & recursion):
21 list_files(fullname, wirldcard, recursion)
22 else:
23 for ext in exts:
24 if (name.endswith(ext)):
25 files_text.append(fullname)
26 break
27 # print files_text
28 return files_text
29
30
31 def count(file):
32 blank_num = 0
33 code_num = 0
34 annotations_num = 0
35 line_num = 0
36 annotations_nums = list()
37 with open(file) as fp:
38 for line in fp.readlines():
39 line_num += 1
40 line = line.strip('\n')
41 if '#' in line:
42 annotations_num += 1
43 if "'''" in line:
44 annotations_nums.append(line_num)
45 elif len(line) > 0:
46 code_num += 1
47 else:
48 blank_num += 1
49
50 fp.close()
51
52 j = 0
53 result = 0
54 for i in annotations_nums:
55 j += 1
56 if j % 2 == 0:
57 result += int(i) - annotations_nums[j - 2]
58 return code_num, annotations_num + result + 1, blank_num
59
60
61 if __name__ == '__main__':
62 files = list_files('G://code')
63 for file in files:
64 count_result = count(file)
65 dic = dict(zip(['code_num', 'annotations_num', 'blank_num'], list(count_result)))
66 print dic