#coding=gbk import os #rootdir=‘f:\\pylianxi‘ def count_line_core(file_name): ##传入单个文件,统计行数,之后返回该文件的实际代码行数;区分utf-8、gbk有待优化 print(‘core_file_name:‘,file_name) lines_count=0 flag=True try: with open(file_name,‘r‘,encoding=‘gbk‘) as fp: print(‘gbk file_name:‘,file_name) for i in fp: i=i.strip() if i=="‘‘‘" or i==‘"""‘: if flag==True: flag=False continue else: flag=True continue elif (i.startswith("‘‘‘") and i.endswith("‘‘‘")) or (i.startswith(‘"""‘) and i.endswith(‘"""‘)): continue elif i.startswith("‘‘‘") or i.startswith(‘"""‘) or i.endswith("‘‘‘") or i.endswith(‘"""‘): if flag==True: flag=False continue else: flag=True continue if flag==True and i!=‘‘ and not i.startswith(‘#‘): lines_count+=1 #print(i) if i.startswith(‘#-*-‘) or i.startswith(‘#coding‘) or i.startswith(‘#encoding‘): lines_count+=1 #print(i) except: with open(file_name,‘r‘,encoding=‘utf-8‘) as fp: print(‘utf-8 file_name:‘,file_name) for i in fp: i=i.strip() if i=="‘‘‘" or i==‘"""‘: if flag==True: flag=False continue else: flag=True continue elif (i.startswith("‘‘‘") and i.endswith("‘‘‘")) or (i.startswith(‘"""‘) and i.endswith(‘"""‘)): continue elif i.startswith("‘‘‘") or i.startswith(‘"""‘) or i.endswith("‘‘‘") or i.endswith(‘"""‘): if flag==True: flag=False continue else: flag=True continue if flag==True and i!=‘‘ and not i.startswith(‘#‘): lines_count+=1 #print(i) if i.startswith(‘#-*-‘) or i.startswith(‘#coding‘) or i.startswith(‘#encoding‘): lines_count+=1 #print(i) return lines_count def code_line_count(rootdir,filetype): ##分别处理了传入的路径是单个文件,或者传入的是文件夹 #rootdir 传的是单个文件 count_dict={} if os.path.isfile(rootdir) and os.path.splitext(rootdir)[1] in filetype: file_name=rootdir lines_count=count_line_core(file_name) return lines_count elif os.path.isdir(rootdir): for files in os.listdir(rootdir): file_name=os.path.join(rootdir,files) if os.path.splitext(file_name)[1] in filetype: print(‘file_name‘,file_name) lines_count=count_line_core(file_name) count_dict[files]=lines_count sum_1=sum(count_dict.values()) return sum_1,count_dict import sys if __name__==‘__main__‘: if len(sys.argv)<3: print(‘参数数量不对,请输入要统计代码行数的文件路径及文件类型,如.txt .py等!‘) sys.exit() if os.path.exists(sys.argv[1]): if os.path.isfile(sys.argv[1]): print(‘该文件的代码行数为:‘,code_line_count(sys.argv[1],sys.argv[2:])) elif os.path.isdir(sys.argv[1]): print(‘sys.argv[1],sys.argv[2:]‘,sys.argv[1],sys.argv[2:]) result=code_line_count(sys.argv[1],sys.argv[2:]) print(‘总代码行数为:%s,每个文件代码行数为:%s‘%result) #for i in result[1]: print(‘*‘*20) print(sorted(result[1].items(),key=lambda x:x[1])) else: print(‘输入的路径不存在,请重新输入!‘) sys.exit()
原文地址:https://www.cnblogs.com/xiaoxiao075/p/10186834.html
时间: 2024-10-06 17:51:03