统计python文件中的代码,注释,空白对应的行数

时间:2021-10-18 03:47:13

其实代码和空白行很好统计,难点是注释行

python中的注释分为以#开头的单行注释

或者以'''开头以'''结尾 或以"""开头以"""结尾的文档注释,如:

'''

hello world

'''和

'''

hello world'''

思路是用is_comment记录是否存在多行注释,如果不存在,则判断当前行是否以'''开头,是则将is_comment设为True,否则进行空行、当前行注释以及代码行的判断,如果is_comment已经为True即,多行注释已经开始,则判断当前行是否以'''结尾,是则将is_comment设为False,同时增加注释的行数。表示多行注释已经结束,反之继续,此时多行注释还未结束

path = 'test.py'
with open(path,'r',encoding='utf-8') as f:
code_lines = 0 #代码行数
comment_lines = 0 #注释行数
blank_lines = 0 #空白行数 内容为'\n',strip()后为''
is_comment = False
start_comment_index = 0 #记录以'''或"""开头的注释位置
for index,line in enumerate(f,start=1):
line = line.strip() #去除开头和结尾的空白符      #判断多行注释是否已经开始 
if not is_comment:
if line.startswith("'''") or line.startswith('"""'):
is_comment = True
start_comment_index = index #单行注释
elif line.startswith('#'):
comment_lines += 1
#空白行
elif line == '':
blank_lines += 1
#代码行
else:
code_lines += 1 #多行注释已经开始
else:
if line.endswith("'''") or line.endswith('"""'):
is_comment = False
comment_lines += index - start_comment_index + 1
else:
pass print("注释:%d" % comment_lines)
print("空行:%d" % blank_lines)
print("代码:%d" % code_lines)