# -*- coding:utf-8 -*-
#!python3
from collections import Counter
path=input("输入文件地址")
def countLines(fileName):#统计代码总行数
count = 0
with open(fileName, 'rb') as f:
while True:
line = f.readline()
if line:
if len(line)>1:
count += 1
else:
break
#print ">>>%s \tLines %d"%(os.path.split(fileName)[1], count)
return count
all_lines=countLines(path)
with open(path,'rb') 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(b"'''") or line.startswith(b'"""'):
is_comment = True
start_comment_index = index
#单行注释
elif line.startswith(b'#'):
comment_lines += 1
# #空白行,网上抄的,不知道为什么不生效
# elif line == '':
# blank_lines += 1
#代码行
else:
code_lines += 1
#多行注释已经开始
else:
if line.endswith(b"'''") or line.endswith(b'"""'):
is_comment = False
comment_lines += index - start_comment_index + 1
else:
pass
with open(path, 'rb') as f:
counter = Counter(1 for line in f if not line.strip())#chatgpt推荐统计文件空白行的代码
# print('This file contains', counter[1], 'blank lines.')
print("注释:%d" % comment_lines)
print("空行:%d" % counter[1])
print("代码:%d" % code_lines)
print("总代码:%d" % all_lines)
# print("空:%d" % blank_lines)
python脚本统计代码出现的空白行/代码/注释
最新推荐文章于 2023-06-11 01:47:38 发布