'''
有个目录,里面是你自己写过的程序,
统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
'''
import os, re
def statistic_info(f):
'''
statistic the info of a file, include:
the number of the lines
the number of the blank lines
the number of the comment lines(single-line or multiLine comment)
'''
comment_lines = 0
blank_lines = 0
lines = 0
is_multicomm = False # statistic multiLine comment
for line in f:
# the current line is not in multiLine comment
if is_multicomm == False:
if re.match('^\s+$', line): # is blank line
blank_lines = blank_lines + 1
elif line.lstrip().startswith('#'): # single-line comment
comment_lines = comment_lines + 1
elif line.lstrip().startswith("'''") or line.lstrip().startswith('"""'): # multiLine comment
comment_lines = comment_lines + 1
is_multicomm = True # note the current line is the beginning of the multiLine comment
# the current line is in multiLine comment
elif is_multicomm == True:
comment_lines = comment_lines + 1
if line.lstrip().startswith("'''") or line.lstrip().startswith('"""'):
is_multicomm = False # note the current line is the end of the multiLine comment
lines = lines + 1
return lines, blank_lines, comment_lines
if __name__ == '__main__':
path = 'Sources'
source_codes = os.listdir(path) # Return a list containing the names of the files in the directory.
lines = 0
blank_lines= 0
comment_lines = 0
lines_total = 0
blank_total = 0
comment_total = 0
for source_code in source_codes:
print('%s' % (40 * '-'))
with open(os.path.join(path, source_code), 'r', encoding = 'utf-8') as f:
lines, blank_lines, comment_lines = statistic_info(f)
print(source_code + ':')
print('lines: ', lines)
print('blank lines: ', blank_lines)
print('comment linse: ', comment_lines)
lines_total = lines_total + lines
blank_total = blank_total + blank_lines
comment_total = comment_total + comment_lines
print('\nthe all source code:')
print('lines_total: ', lines_total)
print('blank_lines_total: ', blank_total)
print('commet_linse_total: ', comment_total)