不忘初心,方得始终

第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。

思路:获取目录,然后遍历目录下的代码文件,逐个统计每个文件的代码,然后最后汇总输出。

0007.统计代码.py

os, re# 代码所在目录FILE_PATH = :”’打开一个py文件,统计其中的代码行数,包括空行和注释返回含该文件总行数,注释行数,,空行数的列表”’total_line = 0comment_line = 0blank_line = 0with open(codefilesource) as f:lines = f.readlines()total_line = len(lines)line_index = line_index < total_line:line = lines[line_index]# 检查是否为注释if line.startswith(“#”):comment_line += :comment_line += :line = lines[line_index]comment_line += 1line_index += line == “\n”:blank_line += 1line_index += % codefilesourceprint “代码行数:”, total_lineprint “注释行数:”, comment_line, “占%0.2f%%” % (comment_line*100.0/total_line)print “空行数: “, blank_line, “占%0.2f%%” % (blank_line*100.0/total_line)return [total_line, comment_line, blank_line]:# 切换到code所在目录os.chdir(FILE_PATH)# 遍历该目录下的py文件total_lines = 0total_comment_lines = 0total_blank_lines = 0for i in os.listdir(os.getcwd()):if os.path.splitext(i)[1] == ‘.py’: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_linesprint “总注释行数:”, total_comment_lines, “占%0.2f%%” % (total_comment_lines*100.0/total_lines)print “总空行数: “, total_blank_lines, “占%0.2f%%” % (total_blank_lines*100.0/total_lines)if __name__ == ‘__main__’:run(FILE_PATH)

效果:

明天的希望,让我们忘了今天的痛苦

不忘初心,方得始终

相关文章:

你感兴趣的文章:

标签云: