這篇文章將為大家詳細講解有關python如何實現代碼統計程序,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
# encoding="utf-8" """ 統計代碼行數 """ import sys import os def count_file_line(path): """統計文件的有效行數""" countLine = 0 # 設置一個標志位,當遇到以"""或者'''開頭或者結尾的時候,置為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: # 空行不統計 if line.strip(): line = line.strip() # 注意下面的這兩個elif必須要前面,這樣子當('"""')結束之后及時將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 # 如果以“#”號開頭的,不統計 elif line.startswith("#"): continue # 如果同時以("'''")或者('"""')開頭或者結尾(比如:"""aaa"""),那么不統計 elif line.startswith('"""') and line.endswith('"""') and line != '"""': continue elif line.startswith("'''") and line.endswith("'''") and line != "'''": continue # 如果以("'''")或者('"""')開頭或者結尾(比如:aaa"""或者"""bbb),那么不統計 # 注意下面的這兩個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=[]): """統計所有文件代碼行""" # 判斷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__": # 打印出命令行輸入的參數 # 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))
關于“python如何實現代碼統計程序”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
本文題目:python如何實現代碼統計程序-創新互聯
網頁路徑:http://m.kartarina.com/article48/ccggep.html
成都網站建設公司_創新互聯,為您提供軟件開發、全網營銷推廣、營銷型網站建設、網站營銷、ChatGPT、動態網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯