用python寫的程式碼統計工具。檔案名稱為counter.py。可以統計代碼檔案中的注釋行、程式碼、空行和總行數。目前支援注釋為//, /*...*/類型和注釋為#類型的程式設計語言程式碼統計。使用方法:
在counter.py的同級目錄建立一個檔案,命名為filelist.txt,在該檔案中輸入需統計的代碼檔案的絕對路徑和檔案名稱。如c:/test.c。每個檔案名稱佔一行。
counter.py代碼如下:
import recommentline = 0blankline = 0codeline = 0def init(): global commentline, blankline, codeline commentline = 0 blankline = 0 codeline = 0def output(filename): global commentline, blankline, codeline print print "/*********************************************/" print "file name: " , filename print "code line: ", codeline print "comment line: ", commentline print "blank line: ", blankline print "total line: ", codeline + commentline + blankline print "/*********************************************/" def count_c_like(filename): try: f = open(filename, 'r') except IOError, e: print print e return None global commentline, blankline, codeline iscomment = False for eachLine in f: if iscomment: commentline += 1 if eachLine.find("*/", 0) != -1: iscomment = False elif re.match(" *//", eachLine) is not None: commentline += 1 elif re.match(" */\*", eachLine) is not None: commentline += 1 if re.search("/\*.*\*/", eachLine) is None: iscomment = True elif eachLine.isspace(): blankline += 1 else: codeline += 1 f.close() return "OK"def count_mk_like(filename): try: f = open(filename, 'r') except IOError, e: print print e return None global commentline, blankline, codeline for eachLine in f: if eachLine.isspace(): blankline += 1 elif re.match(" *#", eachLine) is not None: commentline += 1 else: codeline += 1 f.close() return "OK" def main(): try: f = open("filelist.txt", 'r') except IOError, e: print e raw_input('Press ENTER key to exit') return None global filename for eachLine in f: filename = eachLine.strip() if filename == '': continue init() result = "OK" if re.search("\.min$|\.mk$", filename) is not None: result = count_mk_like(filename) else: result = count_c_like(filename) if result == "OK": output(filename) f.close() raw_input('Press ENTER key to exit')if __name__ == '__main__': main()