python脚本统计代码出现的空白行/代码/注释

# -*- 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)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值