Python Show-Me-the-Code 第 0007 題 代碼統計

來源:互聯網
上載者:User

標籤: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 題 代碼統計

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.