1- # Compute the line number of codes in one directory
1+ #!/usr/bin/python
22
33import os
44
55
6+ file_suffix = "not defined"
7+ inline_comment_syntax = "not defined"
8+ multiline_comment_syntax = "not defined"
9+ result = {"Code files" : 0 ,
10+ "Total lines" : 0 ,
11+ "Code lines" : 0 ,
12+ "Comment lines" : 0 ,
13+ "Blank lines" : 0 }
14+
15+
616def getFilesList (directory ):
717 file_paths = []
818
@@ -13,11 +23,18 @@ def getFilesList(directory):
1323
1424 return file_paths
1525
16- full_file_paths = getFilesList ("D:/PythonProjects/python" )
17- # print("\n".join(full_file_paths))
1826
19- file_type = "python"
20- inline_comment_syntax = "#"
27+ def getSuffix (full_file_path ):
28+ return os .path .splitext (full_file_path )[1 ][1 :]
29+
30+
31+ def identifyFileType (suffix ):
32+ if suffix == "py" :
33+ return "#" , "\" \" \" "
34+ elif suffix == "c" or suffix == "h" or suffix == "cpp" or suffix == "hpp" :
35+ return "//" , "/*"
36+ else :
37+ return "not defined"
2138
2239
2340def isInlineComment (string_line ):
@@ -27,9 +44,55 @@ def isInlineComment(string_line):
2744 :returns: true or false
2845
2946 """
30- if string_line [0 ] == inline_comment_syntax :
47+ commentLen = len (inline_comment_syntax )
48+ if string_line [0 :commentLen ] == inline_comment_syntax :
49+ return True
50+ else :
51+ return False
52+
53+
54+ def isMultilineComment (string_line ):
55+ commentLen = len (str (multiline_comment_syntax ))
56+ if string_line [0 :commentLen ] == multiline_comment_syntax :
3157 return True
3258 else :
3359 return False
3460
35- # print(isInlineComment("# this is a test"))
61+
62+ def countOneFile (full_file_path ):
63+ global inline_comment_syntax , multiline_comment_syntax
64+ file_suffix = getSuffix (full_file_path )
65+ if (identifyFileType (file_suffix ) != "not defined" ):
66+ result ["Code files" ] += 1
67+
68+ (inline_comment_syntax ,
69+ multiline_comment_syntax ) = identifyFileType (file_suffix )
70+ with open (full_file_path , "r" ) as lines :
71+ for line in lines :
72+ line = line .strip ()
73+ if line .strip ():
74+ result ["Total lines" ] += 1
75+ if isInlineComment (line ):
76+ result ["Comment lines" ] += 1
77+ elif isMultilineComment (line ):
78+ result ["Comment lines" ] += 1
79+ else :
80+ result ["Code lines" ] += 1
81+ else :
82+ result ["Blank lines" ] += 1
83+
84+
85+ def countInDirectory (directory ):
86+ full_file_paths = getFilesList (directory )
87+ for f in full_file_paths :
88+ countOneFile (f )
89+
90+ directory = input ()
91+ # countOneFile("d:/NOTBACKEDUP/python/zeyue/0007/ComputeCodeLines.py")
92+ countInDirectory (directory )
93+ # countInDirectory("D:/Documents/Zeyue/workspace/Gauge/v1.3.10\
94+ # /Recorder/QuartzDyne/src")
95+ # countOneFile("D:/Documents/Zeyue/workspace/Gauge/v1.3.10\
96+ # /Recorder/QuartzDyne/src/CommandTable.c")
97+
98+ print (str (result ))
0 commit comments