PythonShowMeTheCode(0007): 统计代码行

2016-08-25  本文已影响0人  tyrone_li

1. 题目

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

2. 思路

3. 实现

# -*- coding: utf-8 -*-
import os
import os.path
import re


def count_code_lines(path):
    if path is None:
        return

    count_code = 0
    count_null = 0
    count_comment = 0
    files = [os.path.join(path, x) for x in os.listdir(path) if os.path.splitext(x)[1] == ".py"]
    for file in files:
       with open(file, encoding="utf-8") as f:
           lines = f.readlines() 
           for line in lines:
                print(line)
                count_code += 1
                if len(line) == line.count("\n"):
                    count_null += 1
                if len(re.findall(r"^\s*#", line)) > 0:
                    count_comment += 1
            if lines[-1][-1:] == "\n":
                count_null += 1

    print("BLANK: %s" % count_null)
    print("COMMENT: %s" % count_comment)
    print("CODE: %s" % (count_code - count_null - count_comment))


if __name__ == "__main__": 
   count_code_lines(".")
上一篇下一篇

猜你喜欢

热点阅读