python統(tǒng)計(jì)指定目錄內(nèi)文件的代碼行數(shù)
python統(tǒng)計(jì)指定目錄內(nèi)文件的代碼行數(shù),程序?qū)崿F(xiàn)統(tǒng)計(jì)指定目錄內(nèi)各個python文件的代碼總行數(shù),注釋行數(shù),空行數(shù),并算出所占百分比
這符合一些公司的小需求,實(shí)際代碼量的統(tǒng)計(jì)工作
效果如圖


代碼如下:
#coding:utf-8
import os,re
#代碼所在目錄
FILE_PATH = './'
def analyze_code(codefilesource):
'''
打開一個py文件,統(tǒng)計(jì)其中的代碼行數(shù),包括空行和注釋
返回含該文件總行數(shù),注釋行數(shù),空行數(shù)的列表
: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("代碼行數(shù):",total_line)
print("注釋行數(shù):",comment_line,"占%0.2f%%"%(comment_line*100/total_line))
print("空行數(shù):", 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("總代碼行數(shù):",total_lines)
print("總注釋行數(shù):",total_comment_lines,"占%0.2f%%"%(total_comment_lines*100/total_lines))
print("總空行數(shù):", total_blank_lines, "占%0.2f%%"% (total_blank_lines * 100 / total_lines))
if __name__ == '__main__':
run(FILE_PATH)
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的小工具
- python實(shí)現(xiàn)代碼統(tǒng)計(jì)器
- python實(shí)現(xiàn)代碼統(tǒng)計(jì)程序
- python tkinter圖形界面代碼統(tǒng)計(jì)工具(更新)
- python3使用GUI統(tǒng)計(jì)代碼量
- python tkinter圖形界面代碼統(tǒng)計(jì)工具
- 使用Python設(shè)計(jì)一個代碼統(tǒng)計(jì)工具
- Python實(shí)現(xiàn)統(tǒng)計(jì)代碼行的方法分析
- python 統(tǒng)計(jì)代碼行數(shù)簡單實(shí)例
- Python實(shí)現(xiàn)代碼統(tǒng)計(jì)工具
相關(guān)文章
深入了解Python中Pytest Markers的使用方法
從這篇開始,逐一解決fixture是啥,mark是啥,參數(shù)request是啥,鉤子函數(shù)是啥,parametrize參數(shù)化是啥,這些問題,本片先介紹一下mark是啥,以及如何使用2023-09-09
詳解如何使用numpy提高Python數(shù)據(jù)分析效率
NumPy是Python語言的一個第三方庫,其支持大量高維度數(shù)組與矩陣運(yùn)算。本文主要為大家介紹了如何使用numpy提高python數(shù)據(jù)分析效率,需要的可以參考一下2023-04-04
手把手教你利用opencv實(shí)現(xiàn)人臉識別功能(附源碼+文檔)
最近搞一個人臉識別的項(xiàng)目練練手,不得不感嘆opencv做人臉檢測實(shí)在是強(qiáng),這篇文章主要給大家介紹了關(guān)于利用opencv實(shí)現(xiàn)人臉識別功能的相關(guān)資料,并附上了源碼以及文檔,需要的朋友可以參考下2021-09-09
python?Pandas之DataFrame索引及選取數(shù)據(jù)
這篇文章主要介紹了python?Pandas之DataFrame索引及選取數(shù)據(jù),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-07-07
Python文件遍歷os.walk()與os.listdir()使用及說明
這篇文章主要介紹了Python文件遍歷os.walk()與os.listdir()使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11

