本文實例為大家分享了Python實現代碼統計工具的具體代碼,供大家參考,具體內容如下
思路:首先獲取所有文件,然后統計每個文件中代碼的行數,最后將行數相加.
實現的功能:
統計每個文件的行數;
統計總行數;
支持指定統計文件類型,排除不想統計的文件類型;
排除空行;
排除注釋行
import os import sys import os.path #for i in sys.argv: # print (i) # 判斷單個文件的代碼行數 def count_file_lines(file_path): line_count = 0 flag=True try: fp = open(file_path,"r",encoding="utf-8") encoding_type="utf-8" fp.close() except: encoding_type="gbk" with open(file_path,"r",encoding=encoding_type) as fp: for line in fp: #print (line_count) if line.strip()=="": continue else: if line.strip().endswith("'''") and flag == False: flag=True continue if line.strip().endswith('"""') and flag == False: flag=True continue if flag == False: continue if line.strip().startswith("#encoding") or line.strip().startswith("#-*-"): line_count += 1 #elif line.strip().startswith('"""') and line.strip().endswith('"""') and line.strip()!='"""': #continue #elif line.strip().startswith("'''") and line.strip().endswith("'''") and line.strip()!="'''": #continue elif line.strip().startswith('#'): continue elif line.strip().startswith("'''") and flag == True: flag = False continue elif line.strip().startswith('"""') and flag == True: flag = False continue else: line_count += 1 return line_count def count_code_lines(path,file_types=[]): # 判斷路徑是否存在 if not os.path.exists(path): print("您輸入的目錄或文件路徑不存在") return 0 line_count=0 #代碼行總數 file_lines_dict={} #每個文件代碼行數 # 判斷是否為文件 if os.path.isfile(path): file_type = os.path.splitext(path)[1][1:] #取到文件后綴名 # 判斷文件類型是否滿足條件 if len(file_types)==0: file_types=["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"] if file_type in file_types: line_count = count_file_lines(path) return line_count else: file_path = [] for root, dirs, files in os.walk(path): for file in files: file_path.append(os.path.join(root,file)) for f in file_path: file_type = os.path.splitext(f)[1][1:] if len(file_types)==0: file_types= ["py","cpp","c","java","ruby","ini","go","html","css","js","txt","vbs","php","asp","sh"] if file_type not in file_types: continue line_num = count_file_lines(f) line_count += line_num file_lines_dict[f] = line_num return line_count,file_lines_dict if __name__=="__main__": print (sys.argv) if len(sys.argv) < 2: print ("請輸入待統計行數的代碼絕對路徑!") sys.exit() count_path = sys.argv[1] file_types = [] if len(sys.argv) >2: for i in sys.argv[2:]: file_types.append(i) #print(count_path,file_types) print(count_code_lines(count_path,file_types)) #print(count_file_lines("b.py"))
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
