刚才突然想统计一下自己写的代码中有效代码数量,也好久没在这上面写博客了(播客搬家了),然后就有了此文。
代码如下(有bug请指出):
一、直接python demo.py运行
二、或者 import demo
demo.run("你的源码地址")
#!/usr/bin/env python #coding=utf-8 import os,re #代码所在目录 FILE_PATH = "D:\\sublime text workplace\\java\\" def _analyze_code(codefilesource): ''' 打开py文件,统计代码行数,包括空行和注释 ''' total_line = 0 comment_line = 0 blank_line = 0 with open(codefilesource,'r+',encoding="UTF-8") as f: lines = f.readlines() total_line = len(lines) line_index = 0 #遍历每一行 while line_index < total_line: line = lines[line_index] #检查是否为注释 if line.startswith("#") or re.match(r"^\s*//",line): comment_line += 1 elif re.match(r"\s*'''",line) is not None: comment_line += 1 while re.match(r".*'''$",line) is None: line = lines[line_index] comment_line += 1 line_index += 1 elif re.match(r"\s*/\*+",line): comment_line +=1 while re.match(r"\*/",line): line = lines[line_index] comment_line += 1 line_index += 1 #检查是否为空行 elif line == "\n" or re.match("^\s*$",line): blank_line += 1 line_index +=1 print("在%s中 : "% codefilesource) print("代码行数 :",total_line) print("注释行数 :",comment_line,"占%0.2f%%"%(comment_line*100.0/(total_line if total_line!=0 else 1))) print("空行数: ",blank_line,"占%0.2f%%"%(blank_line*100.0/(total_line if total_line!=0 else 1))) return [total_line,comment_line,blank_line] def run(FILE_PATH): #切换到所在目录 os.chdir(FILE_PATH) total_lines = 0 total_comment_lines = 0 total_blank_lines = 0 for i in os.listdir(os.getcwd()): if os.path.splitext(i)[1] == '.py' or os.path.splitext(i)[1] == '.java': line = _analyze_code(i) total_lines,total_comment_lines,total_blank_lines = total_lines + line[0], total_comment_lines + line[1], total_blank_lines + line[2] print("总代码行数 :",total_lines) print("总注释行数:",total_comment_lines, "占%0.2f%%" % (total_comment_lines*100.0/total_lines if total_lines!=0 else 100)) print("总空行数:",total_blank_lines, "占%0.2f%%" % (total_blank_lines*100.0/total_lines if total_lines!=0 else 100)) if __name__ == '__main__': run(FILE_PATH)