Python练习册(七)——统计代码行数注释

problem0007统计代码行数注释

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

  • os模块方法得到目录下自己的程序文件
  • 读取每个文件,分别统计代码行、空行和注释

demo:

#!/bin/python3

import os
import re

def get_files():                        #get all py files
    files = os.listdir(os.getcwd())
    py_list=[]
    for f in files:
        if f.split('.')[-1] == 'py':
            print("This py is:",f)
            py_list.append(f)
    return py_list

def count(files):                       #count lines,blank and comments
    code_line,blank,comments = 0,0,0
    for fname in files:
        f = open(fname,'r')
        for line in f:           
            code_line += 1
            if line == '\n':
                blank +=1
            if re.search(r'#',line):
                comments +=1
        f.close()
    return [code_line,blank,comments]

if __name__ == '__main__' :
    files = get_files()
    lines = count(files)
    print("Alright,the result is : Lines(s): %d ,blank: %d, comments: %d" % (lines[0],lines[1],lines[2]))  

参考:Show me the code_0007题

效果:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_30650153/article/details/80866931