原題
有個目錄幔摸,里面是你自己寫過的程序,統(tǒng)計一下你寫過多少行代碼。包括空行和注釋
collections
collections是Python內(nèi)建的一個集合模塊,提供了許多有用的集合類
其中Counter
可以很方便的實現(xiàn)計數(shù)功能
對于Counter
:
-
創(chuàng)建
-
c = Counter()
創(chuàng)建空的計數(shù)器 -
c = Counter('gallahad')
使用可迭代對象創(chuàng)建計數(shù)器 -
c = Counter({'red': 4, 'blue': 2})
使用集合創(chuàng)建計數(shù)器 -
c = Counter(cats=4, dogs=8)
使用關(guān)鍵字創(chuàng)建計數(shù)器
-
-
elements()
c = Counter(a=4, b=2, c=0, d=-2) list(c.elements()) result ['a', 'a', 'a', 'a', 'b', 'b']
按照計數(shù)器中的數(shù)值重復(fù)key生成迭代對象
-
most_common(n)
Counter('abracadabra').most_common(3) result [('a', 5), ('r', 2), ('b', 2)]
取出計數(shù)器中數(shù)量最多的n個元素
-
subtract
c = Counter(a=4, b=2, c=0, d=-2) d = Counter(a=1, b=2, c=3, d=4) c.subtract(d) c result Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
兩個計數(shù)器的數(shù)值相減
os
python操作操作系統(tǒng)提供的接口函數(shù)
-
path
封裝了對文件路徑的一些操作庸汗,如path.splitext()
可以獲取文件和文件擴展名 -
walk
可以遍歷目錄,獲取其中的根目錄手报,文件夾蚯舱,文件
代碼
"""
有個目錄,里面是你自己寫過的程序掩蛤,統(tǒng)計一下你寫過多少行代碼枉昏。包括空行和注釋,但是要分別列出來揍鸟。
"""
from os import walk, path
from collections import Counter
counter = Counter(class_num=0, code_lines=0, space_lines=0, comments_lines=0)
def get_lines_from_java_file(path):
with open(path) as f:
for line in f:
counter['code_lines'] += 1
if line == '\n':
counter['space_lines'] += 1
elif line.startswith('/') or line.startswith('*'):
counter['comments_lines'] += 1
counter['code_lines'] += 1
def get_java_file_paths(workspace_path):
for root, dirs, files in walk(workspace_path):
for filename in files:
postfix = path.splitext(filename)[1]
if postfix == '.java':
counter['class_num'] += 1
file_path = path.join(root, filename)
get_lines_from_java_file(file_path)
if __name__ == '__main__':
workspace_path = '/Users/Mac/Desktop/Xinjr/app/src/main/java'
get_java_file_paths(workspace_path)
print(counter)