
這篇文章將為大家詳細講解有關(guān)python如何實現(xiàn)代碼統(tǒng)計程序,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
# encoding="utf-8"
"""
統(tǒng)計代碼行數(shù)
"""
import sys
import os
def count_file_line(path):
"""統(tǒng)計文件的有效行數(shù)"""
countLine = 0
# 設置一個標志位,當遇到以"""或者'''開頭或者結(jié)尾的時候,置為False
flag = True
# 使用utf-8格式的編碼方式讀取文件,如果讀取失敗,將使用gbk編碼方式讀取文件
try:
fp = open(path, "r", encoding="utf-8")
encoding_type = "utf-8"
fp.close()
except:
encoding_type = "gbk"
with open(path, "r", encoding=encoding_type) as fp:
for line in fp:
# 空行不統(tǒng)計
if line.strip():
line = line.strip()
# 注意下面的這兩個elif必須要前面,這樣子當('"""')結(jié)束之后及時將flag置為True
if line.endswith('"""') and flag == False:
flag = True
continue
if line.endswith("'''") and flag == False:
flag = True
continue
if flag == False:
continue
if line.startswith("#!") or line.startswith("#-*-") or line.startswith("# encoding"):
countLine += 1
# 如果以“#”號開頭的,不統(tǒng)計
elif line.startswith("#"):
continue
# 如果同時以("'''")或者('"""')開頭或者結(jié)尾(比如:"""aaa"""),那么不統(tǒng)計
elif line.startswith('"""') and line.endswith('"""') and line != '"""':
continue
elif line.startswith("'''") and line.endswith("'''") and line != "'''":
continue
# 如果以("'''")或者('"""')開頭或者結(jié)尾(比如:aaa"""或者"""bbb),那么不統(tǒng)計
# 注意下面的這兩個elif必須要放后面
elif line.startswith('"""') and flag == True:
flag = False
continue
elif line.startswith("'''") and flag == True:
flag = False
continue
else:
countLine += 1
return countLine
def count_codes(path,file_types=[]):
"""統(tǒng)計所有文件代碼行"""
# 判斷path是目錄還是文件,如果是目錄的話,遍歷目錄下所有的文件
if not os.path.exists(path):
print("您輸入的路徑不存在!")
return 0
countTotalLine = 0
file_paths = {}
if os.path.isdir(path):
for root,dirs,files in os.walk(path):
for name in files:
if not file_types:
file_types = ["txt","py"]
# print(file_types)
if os.path.splitext(name)[1][1:] in file_types:
file_path = os.path.normpath(os.path.join(root,name))
# print(file_path)
file_lines = count_file_line(file_path)
countTotalLine += file_lines
file_paths[file_path] = file_lines
else:
if not file_types:
file_types = ["txt","py"]
if os.path.splitext(path)[1][1:] in file_types:
countTotalLine = count_file_line(path)
file_paths[path] = count_file_line(path)
return countTotalLine,file_paths
if __name__ == "__main__":
# 打印出命令行輸入的參數(shù)
# print(sys.argv)
if len(sys.argv) < 2:
print("請輸入路徑!")
sys.exit()
path = sys.argv[1]
# print(path)
file_types = sys.argv[2:]
# print(file_types)
print(count_codes(path,file_types))關(guān)于“python如何實現(xiàn)代碼統(tǒng)計程序”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
本文題目:python如何實現(xiàn)代碼統(tǒng)計程序-創(chuàng)新互聯(lián)
網(wǎng)頁路徑:http://chinadenli.net/article48/ccggep.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、全網(wǎng)營銷推廣、營銷型網(wǎng)站建設、網(wǎng)站營銷、ChatGPT、動態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容