首页 > 编程 > Python > 正文

python实现代码统计器

2019-11-25 11:41:44
字体:
来源:转载
供稿:网友

本文实例为大家分享了python中的代码行数统计,供大家参考,具体内容如下

思路:统计文件中代码的总行数减去空行单行注释以及多行注释

功能:

1.获取文件内容的总行数

2.排除空行 单行注释 多行注释

def code_statistics(path): # # 打开这个文件 with open(path, 'r', encoding='utf-8') as openFile:  # 按列读取  fileline = openFile.readlines()  # 给非代码行一个变量  i = 0  # 整个文件里面内容的总行数  number_line = len(fileline)  # 给多行注释一个状态  note = False  # 遍历文件内容  for line in fileline:   # 空行   if line == '/n':    i += 1   # 单行注释   elif re.findall('[#]', line):    i += 1   # 多行注释开头   elif re.findall("/'/'/'", line) and note == False:    i += 1    note = True   # 多行注释结尾   elif re.findall("/'/'/'", line) and note == True:    i += 1    note = False   # 多行注释内部注释   elif note:    i += 1  num_code_line = number_line - i  print(num_code_line)

如果统计文件夹中的python文件的代码行数,首先就是要遍历文件目录,筛选出以.py结尾的文件,再去统计py文件里面的代码行数

def get_all_fire(path): # 得到当前目录下的所有文件 file_list = os.listdir(path) py_file_abs = [] # 遍历所有文件 for file_name in file_list:  # 获取文件及文件夹的绝对路径  file_abs = os.path.join(path, file_name)  if os.path.isfile(file_abs) and file_name.endswith('.py'): # 判断当前文件路径是否是文件和.py文件   py_file_abs.append(file_abs)   # 判断当前文件路径是不是文件夹  elif os.path.isdir(file_abs):   py_file_abs += get_all_fire(file_abs) return py_file_abs

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表