Python实现统计代码行的方法分析
本篇章节讲解Python实现统计代码行的方法。分享给大家供大家参考,具体如下: 参加光荣之路测试开发班已三月有余,吴总上课也总问“ 咱们的课上了这么多次了大家实践了多少行代码了?”。这里是一个一脸懵逼的表情。该怎么统计呢?一个个文件数当然不可取,能用代码解决的事咱们坚决不动手。最近在网上刷题时也正好遇到有这么一道题,所以决定撸一撸。 题目:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。 首先分析一下思路捋一下大象装冰箱的步骤,从一个给定的目录统计该目录下所有的代码行大致需要以下7个步骤: 1. 遍历该目录下所有的文件。 解题思路捋清楚之后剩下的就是将各模块的代码像搭积木一样搭起来就完事了(示例代码在本文最后): 5~9: 导入OS,定义 code_lines_count 函数并接收一个 path 形式参数,声明了三个变量分别用于统计代码行,注释行和空行 #_*_coding:utf-8_*_ # 统计代码行数,空行,注释. import os def code_lines_count(path): code_lines = 0 comm_lines = 0 space_lines = 0 for root,dirs,files in os.walk(path): for item in files: file_abs_path = os.path.join(root,item) postfix = os.path.splitext(file_abs_path)[1] if postfix == '.py': #print 'Start: ',file_abs_path with open(file_abs_path) as fp: while True: line = fp.readline() if not line: #print 'break here,%r' %line break elif line.strip().startswith('#'): #print '1,here',line comm_lines += 1 elif line.strip().startswith("'''") or line.strip().startswith('"""'): comm_lines += 1 if line.count('"""') ==1 or line.count("'''") ==1: while True: line = fp.readline() #print '4,line comm_lines += 1 if ("'''" in line) or ('"""' in line): break elif line.strip(): #print '5,line code_lines += 1 else: #print '6,line space_lines +=1 #print 'Done',file_abs_path return code_lines,comm_lines,space_lines #test print "Code lines: %dnComments lines: %dnWhiteSpace lines: %d" %code_lines_count(r'D:exercises') --码代码本质和打游戏一样, 都是打怪升级穿装备。 更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》 希望本文所述对大家Python程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |