Python,针对指定文件类型,过滤空行和注释,统计行数

参考网络上代码编辑而成,无技术含量,可自行定制:

目前亲测有效,若有待完善之处,还望指出!

强调:将此统计py脚本放置项目的根目录下执行即可。

1、遍历文件,递归遍历文件夹中的所有

def getFile(basedir):
    global filelists
    for parent,dirnames,filenames in os.walk(basedir):
        #for dirname in dirnames:
        #    getFile(os.path.join(parent,dirname)) #递归
        for filename in filenames:
            ext = filename.split('.')[-1]
            #只统计指定的文件类型,略过一些log和cache文件
            if ext in whitelist:
                filelists.append(os.path.join(parent,filename))

2、指定文件类型:项目的代码行数,故只考虑.py文件,当然也可在指定的文件类型列表whitelist中添加其他类型

# 指定想要统计的文件类型
whitelist = ['py']

3、过滤空行和注释,注意采用的读取文件模式为‘rb’

def countLine(fname):
    count = 0
    single_quotes_flag = False
    double_quotes_flag = False
    with open(fname, 'rb') as f:
        for file_line in f:
            file_line = file_line.strip()
            # print(file_line)
            # 空行
            if file_line == b'':
                pass

            # 注释 # 开头
            elif file_line.startswith(b'#'):
                pass

            # 注释 单引号 ''' 开头
            elif file_line.startswith(b"'''") and not single_quotes_flag:
                single_quotes_flag = True
            # 注释 中间 和 ''' 结尾
            elif single_quotes_flag == True:
                if file_line.endswith(b"'''"):
                    single_quotes_flag = False

            # 注释 双引号 """ 开头
            elif file_line.startswith(b'"""') and not double_quotes_flag:
                double_quotes_flag = True
            # 注释 中间 和 """  结尾
            elif double_quotes_flag == True:
                if (file_line.endswith(b'"""')):
                    double_quotes_flag = False

            # 代码
            else:
                count += 1
        print(fname + '----', count)
        # 单个文件行数
        # print(fname,'----count:',count)
        return count

完整源码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/05/10 21:50
# @Author  : MJay_Lee
# @File    : python统计行数.py
# @Contact : [email protected]

import os
import time
basedir = os.path.dirname(__file__)
filelists = []
# 指定想要统计的文件类型
whitelist = ['py']
#遍历文件, 递归遍历文件夹中的所有
def getFile(basedir):
    global filelists
    for parent,dirnames,filenames in os.walk(basedir):
        #for dirname in dirnames:
        #    getFile(os.path.join(parent,dirname)) #递归
        for filename in filenames:
            ext = filename.split('.')[-1]
            #只统计指定的文件类型,略过一些log和cache文件
            if ext in whitelist:
                filelists.append(os.path.join(parent,filename))
#统计一个文件的行数
def countLine(fname):
    count = 0
    single_quotes_flag = False
    double_quotes_flag = False
    with open(fname, 'rb') as f:
        for file_line in f:
            file_line = file_line.strip()
            # print(file_line)
            # 空行
            if file_line == b'':
                pass

            # 注释 # 开头
            elif file_line.startswith(b'#'):
                pass

            # 注释 单引号 ''' 开头
            elif file_line.startswith(b"'''") and not single_quotes_flag:
                single_quotes_flag = True
            # 注释 中间 和 ''' 结尾
            elif single_quotes_flag == True:
                if file_line.endswith(b"'''"):
                    single_quotes_flag = False

            # 注释 双引号 """ 开头
            elif file_line.startswith(b'"""') and not double_quotes_flag:
                double_quotes_flag = True
            # 注释 中间 和 """  结尾
            elif double_quotes_flag == True:
                if (file_line.endswith(b'"""')):
                    double_quotes_flag = False

            # 代码
            else:
                count += 1
        print(fname + '----', count)
        # 单个文件行数
        # print(fname,'----count:',count)
        return count

if __name__ == '__main__' :
    startTime = time.clock()
    getFile(basedir)
    totalline = 0
    for filelist in filelists:
        totalline = totalline + countLine(filelist)
    print('\033[43m total lines: \033[0m'.center(20,'-'),totalline)
    print('Done! Cost Time: %0.5f second' % (time.clock() - startTime))

测试对象样本,test.py:

# 123
'''
123
aa

哈哈
'''
"""
123
aa
 
哈哈
 
"""
code1
code2

结果为:2

猜你喜欢

转载自www.cnblogs.com/limengjie0104/p/9022605.html
今日推荐