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 : limengjiejj@hotmail.com

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM