python统计指定目录内文件的代码行数

yipeiwu_com5年前Python基础

python统计指定目录内文件的代码行数,程序实现统计指定目录内各个python文件的代码总行数,注释行数,空行数,并算出所占百分比

这符合一些公司的小需求,实际代码量的统计工作

效果如图

代码如下:

#coding:utf-8
import os,re
 
#代码所在目录
FILE_PATH = './'
 
def analyze_code(codefilesource):
  '''
  打开一个py文件,统计其中的代码行数,包括空行和注释
  返回含该文件总行数,注释行数,空行数的列表
  :param codefilesource:
  :return:
  '''
  total_line = 0
  comment_line = 0
  blank_line = 0
  with open(codefilesource,encoding='gb18030',errors='ignore') as f:
    lines = f.readlines()
    total_line = len(lines)
    line_index = 0
    #遍历每一行
    while line_index < total_line:
      line = lines[line_index]
      #检查是否为注释
      if line.startswith("#"):
        comment_line += 1
      elif re.match("\s*'''",line) is not None:
        comment_line += 1
        while re.match(".*'''$",line) is None:
          line = lines[line_index]
          comment_line += 1
          line_index += 1
      #检查是否为空行
      elif line =='\n':
        blank_line += 1
      line_index += 1
  print("在%s中:"%codefilesource)
  print("代码行数:",total_line)
  print("注释行数:",comment_line,"占%0.2f%%"%(comment_line*100/total_line))
  print("空行数:", blank_line, "占%0.2f%%"%(blank_line * 100 / total_line))
  return [total_line,comment_line,blank_line]
def run(FILE_PATH):
  os.chdir(FILE_PATH)
  #遍历py文件
  total_lines = 0
  total_comment_lines = 0
  total_blank_lines = 0
  for i in os.listdir(os.getcwd()):
    if os.path.splitext(i)[1] == '.py':
      line = analyze_code(i)
      total_lines,total_comment_lines,total_blank_lines=total_lines+line[0],total_comment_lines+line[1],total_blank_lines+line[2]
  print("总代码行数:",total_lines)
  print("总注释行数:",total_comment_lines,"占%0.2f%%"%(total_comment_lines*100/total_lines))
  print("总空行数:", total_blank_lines, "占%0.2f%%"% (total_blank_lines * 100 / total_lines))
 
if __name__ == '__main__':
  run(FILE_PATH)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现ID3决策树算法

ID3决策树是以信息增益作为决策标准的一种贪心决策树算法 # -*- coding: utf-8 -*- from numpy import * import math imp...

tensorflow 中对数组元素的操作方法

tensorflow 中对数组元素的操作方法

tensorflow中对tensor对象进行像numpy数组一样便捷的操作是不可能的, 至少对1.2以及之前的版本而言。 从issue上看到,有不少人希望tensorflow能及早实现这...

在Python下进行UDP网络编程的教程

在Python下进行UDP网络编程的教程

TCP是建立可靠连接,并且通信双方都可以以流的形式发送数据。相对TCP,UDP则是面向无连接的协议。 使用UDP协议时,不需要建立连接,只需要知道对方的IP地址和端口号,就可以直接发数据...

Python挑选文件夹里宽大于300图片的方法

本文实例讲述了Python挑选文件夹里宽大于300图片的方法。分享给大家供大家参考。具体分析如下: 这段代码需要用到PIL库。代码如下所示: import sys import os...

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

Python3+PyInstall+Sciter解决报错缺少dll、html等文件问题

1 调试过程 用Python3.6+Sciter+PyCharm写了一个py测试脚本helloworld.py,该脚本中只含有一条语句“import sciter”。在PyCharm中运...