|
| 1 | +#! usr/bin/python3 |
| 2 | +""" |
| 3 | +第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。 |
| 4 | +包括空行和注释,但是要分别列出来。 |
| 5 | +""" |
| 6 | + |
| 7 | +class PyfileInfo: |
| 8 | + |
| 9 | + def __init__(self, file): |
| 10 | + self.file_name = file |
| 11 | + self.total_line_num = 0 |
| 12 | + self.blank_line_num = 0 |
| 13 | + self.comment_line_num = 0 |
| 14 | + |
| 15 | + def count_lines(self): |
| 16 | + if self.file_name[-3:] != '.py': |
| 17 | + print(self.file_name + ' is not a .py file!') |
| 18 | + return |
| 19 | + mc_flag = False |
| 20 | + try: |
| 21 | + with open(self.file_name) as code: |
| 22 | + for each_line in code: |
| 23 | + self.total_line_num += 1 |
| 24 | + temp = each_line.strip() |
| 25 | + if temp == '': |
| 26 | + self.blank_line_num += 1 |
| 27 | + elif temp[0] == '#': |
| 28 | + self.comment_line_num += 1 |
| 29 | + else: |
| 30 | + if False == mc_flag: |
| 31 | + if temp[0:3] == '"""': |
| 32 | + mc_flag = True |
| 33 | + elif temp[-3:] == '"""': |
| 34 | + mc_flag = False |
| 35 | + self.comment_line_num += 1 |
| 36 | + if mc_flag: |
| 37 | + self.comment_line_num += 1 |
| 38 | + except IOError as err: |
| 39 | + print('File error: ' + str(err)) |
| 40 | + |
| 41 | + def display(self): |
| 42 | + print('-.' * 15) |
| 43 | + print('The ' + self.file_name + ' code statistic is:') |
| 44 | + print('Total line number is:', self.total_line_num) |
| 45 | + print('Blank line number is:', self.blank_line_num) |
| 46 | + print('Comment line number is:', self.comment_line_num) |
| 47 | + |
| 48 | +import os |
| 49 | + |
| 50 | +target_path = '../../../python_primer/mrdw/cgi-bin' |
| 51 | +#Get file list from the target directory excluding files in its subdirectories |
| 52 | +file_list = [f for f in os.listdir(target_path) |
| 53 | + if os.path.isfile(os.path.join(target_path, f))] |
| 54 | +#Get .py file list |
| 55 | +pyfile_list = [os.path.join(target_path, f) for f in file_list |
| 56 | + if f[-3:] == '.py'] |
| 57 | + |
| 58 | +Total_line_num = 0 |
| 59 | +Blank_line_num = 0 |
| 60 | +Comment_line_num = 0 |
| 61 | + |
| 62 | +print('==' * 32) |
| 63 | +for each_file in pyfile_list: |
| 64 | + py_file = PyfileInfo(each_file) |
| 65 | + py_file.count_lines() |
| 66 | + py_file.display() |
| 67 | + Total_line_num += py_file.total_line_num |
| 68 | + Blank_line_num += py_file.blank_line_num |
| 69 | + Comment_line_num += py_file.comment_line_num |
| 70 | + |
| 71 | +print('=-' * 24) |
| 72 | +print('All code files in ' + target_path + ' statistic is:') |
| 73 | +print('Total line number is:', Total_line_num) |
| 74 | +print('Blank line number is:', Blank_line_num) |
| 75 | +print('Comment line number is:', Comment_line_num) |
0 commit comments