標籤:python 代碼統計
第 0007 題:有個目錄,裡面是你自己寫過的程式,統計一下你寫過多少行代碼。包括空行和注釋,但是要分別列出來。
思路:擷取目錄,然後遍曆目錄下的代碼檔案,逐個統計每個檔案的代碼,然後最後匯總輸出。
0007.統計代碼.py
#!/usr/bin/env python#coding: utf-8import os, re# 代碼所在目錄FILE_PATH = ‘/home/bill/Desktop/github/show-me-the-code‘def analyze_code(codefilesource): ‘‘‘ 開啟一個py檔案,統計其中的程式碼數,包括空行和注釋 返回含該檔案總行數,注釋行數,空行數的列表 ‘‘‘ total_line = 0 comment_line = 0 blank_line = 0 with open(codefilesource) as f: lines = f.readlines() total_line = len(lines) line_index = 0 # 遍曆每一行 while line_index < total_line: line = lines[line_index] # 檢查是否為注釋 if line.startswith("#"): comment_line += 1 elif re.match("\s*‘‘‘", line) is not None: comment_line += 1 while re.match(".*‘‘‘$", line) is None: line = lines[line_index] comment_line += 1 line_index += 1 # 檢查是否為空白行 elif line == "\n": blank_line += 1 line_index += 1 print "在%s中:" % codefilesource print "程式碼數:", total_line print "注釋行數:", comment_line, "占%0.2f%%" % (comment_line*100.0/total_line) print "空行數: ", blank_line, "占%0.2f%%" % (blank_line*100.0/total_line) return [total_line, comment_line, blank_line]def run(FILE_PATH): # 切換到code所在目錄 os.chdir(FILE_PATH) # 遍曆該目錄下的py檔案 total_lines = 0 total_comment_lines = 0 total_blank_lines = 0 for i in os.listdir(os.getcwd()): if os.path.splitext(i)[1] == ‘.py‘: line = analyze_code(i) total_lines, total_comment_lines, total_blank_lines = total_lines + line[0], total_comment_lines + line[1], total_blank_lines + line[2] print "總程式碼數:", total_lines print "總注釋行數:", total_comment_lines, "占%0.2f%%" % (total_comment_lines*100.0/total_lines) print "總空行數: ", total_blank_lines, "占%0.2f%%" % (total_blank_lines*100.0/total_lines)if __name__ == ‘__main__‘: run(FILE_PATH)
效果:
Python Show-Me-the-Code 第 0007 題 代碼統計