原題
有個(gè)目錄,里面是你自己寫過(guò)的程序,統(tǒng)計(jì)一下你寫過(guò)多少行代碼。包括空行和注釋
collections
collections是Python內(nèi)建的一個(gè)集合模塊,提供了許多有用的集合類
其中Counter可以很方便的實(shí)現(xiàn)計(jì)數(shù)功能
對(duì)于Counter:
-
創(chuàng)建
-
c = Counter()創(chuàng)建空的計(jì)數(shù)器 -
c = Counter('gallahad')使用可迭代對(duì)象創(chuàng)建計(jì)數(shù)器 -
c = Counter({'red': 4, 'blue': 2})使用集合創(chuàng)建計(jì)數(shù)器 -
c = Counter(cats=4, dogs=8)使用關(guān)鍵字創(chuàng)建計(jì)數(shù)器
-
-
elements()c = Counter(a=4, b=2, c=0, d=-2) list(c.elements()) result ['a', 'a', 'a', 'a', 'b', 'b']按照計(jì)數(shù)器中的數(shù)值重復(fù)key生成迭代對(duì)象
-
most_common(n)Counter('abracadabra').most_common(3) result [('a', 5), ('r', 2), ('b', 2)]取出計(jì)數(shù)器中數(shù)量最多的n個(gè)元素
-
subtractc = 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})兩個(gè)計(jì)數(shù)器的數(shù)值相減
os
python操作操作系統(tǒng)提供的接口函數(shù)
-
path封裝了對(duì)文件路徑的一些操作,如path.splitext()可以獲取文件和文件擴(kuò)展名 -
walk可以遍歷目錄,獲取其中的根目錄,文件夾,文件
代碼
"""
有個(gè)目錄,里面是你自己寫過(guò)的程序,統(tǒng)計(jì)一下你寫過(guò)多少行代碼。包括空行和注釋,但是要分別列出來(lái)。
"""
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)