代码参考:https://foofish.net/how-to-count-code.html
import os
def parse(path):
in_multi_comment = False
comments,blanks,codes = 0,0,0
with open(path,'r') as fp:
for scline in fp.readlines():
scline = scline.strip()
if scline == '' and not in_multi_comment:
blanks += 1
elif scline.startswith('//') or \
(scline.startswith("/*") and scline.endswith("*/")) or \
(in_multi_comment and not scline.endswith("*/")):
comments += 1
elif scline.startswith("/*") or scline.endswith("*/"):
in_multi_comment = not in_multi_comment
comments += 1
else:
codes += 1
return {"comments":comments,"blanks":blanks,"codes":codes}
def counter(path):
if os.path.isdir(path):
comments,blanks,codes = 0,0,0
list_dirs = os.walk(path)
for root,dirs,files in list_dirs:
for f in files:
file_path = os.path.join(root,f)
if file_path.endswith(".c") or file_path.endswith(".h"):
stats = parse(file_path)
comments += stats.get("comments")
blanks += stats.get("blanks")
codes += stats.get("codes")
return {"comments":comments,"blanks":blanks,"codes":codes}
else:
return parse(path)
if __name__ == '__main__':
print (counter("你的代码路径"))