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

yipeiwu_com6年前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设计】。

相关文章

PYQT5实现控制台显示功能的方法

PYQT5实现控制台显示功能的方法

界面文件 Ui_ControlBoard.py # -*- coding: utf-8 -*- # Form implementation generated from read...

python自动重试第三方包retrying模块的方法

retrying是一个python的重试包,可以用来自动重试一些可能运行失败的程序段,retrying提供一个装饰器函数retry,被装饰的函数就会在运行失败的情况下重新执行,默认只要一...

Python字符串拼接六种方法介绍

Python字符串拼接的6种方法: 1.加号 第一种,有编程经验的人,估计都知道很多语言里面是用加号连接两个字符串,Python里面也是如此直接用“+”来连接两个字符串; print...

在Python中使用NLTK库实现对词干的提取的教程

在Python中使用NLTK库实现对词干的提取的教程

什么是词干提取? 在语言形态学和信息检索里,词干提取是去除词缀得到词根的过程─—得到单词最一般的写法。对于一个词的形态词根,词干并不需要完全相同;相关的词映射到同一个词干一般能得到满意的...

Python数据分析之双色球基于线性回归算法预测下期中奖结果示例

Python数据分析之双色球基于线性回归算法预测下期中奖结果示例

本文实例讲述了Python数据分析之双色球基于线性回归算法预测下期中奖结果。分享给大家供大家参考,具体如下: 前面讲述了关于双色球的各种算法,这里将进行下期双色球号码的预测,想想有些小激...