python 指令碼(擷取指定檔案夾、指定檔案格式、的程式碼數、注釋行數)

來源:互聯網
上載者:User

標籤:path   main   with   etc   file   imp   ota   注釋   while   

1.代碼的運行結果:

  擷取 指定檔案夾下、指定檔案格式 檔案的: 總程式碼數、總注釋行數(需指定注釋格式)、總空行數;

 1 #coding: utf-8 2 import os, re 3  4 # 代碼所在目錄 5 FILE_PATH = ‘./‘ 6  7 def analyze_code(codefilesource): 8     ‘‘‘ 9         開啟一個py檔案,統計其中的程式碼數,包括空行和注釋10         返回含該檔案總行數,注釋行數,空行數的列表11     ‘‘‘12     total_line = 013     comment_line = 014     blank_line = 015 16     with open(codefilesource) as f:17         lines = f.readlines()#  [‘import aa‘, ‘if main‘, ‘‘]18         total_line = len(lines)19         line_index = 020 21         # 遍曆每一行22         while line_index < total_line:23             line = lines[line_index]24             # 檢查是否為注釋25             if line.startswith("#"):26                 comment_line += 127             # 檢查是否為空白行28             elif line == "\n":29                 blank_line += 130 31             line_index += 132 33     print "在%s中:" % codefilesource34     print "程式碼數:", total_line35     print "注釋行數:", comment_line, "占%0.2f%%" % (comment_line*100.0/total_line)36     print "空行數:  ", blank_line, "占%0.2f%%" % (blank_line*100.0/total_line)37 38     return [total_line, comment_line, blank_line]39 40 41 def run(FILE_PATH):42     # 切換到code所在目錄43     os.chdir(FILE_PATH)44     # 遍曆該目錄下的py檔案45     total_lines = 046     total_comment_lines = 047     total_blank_lines = 048 49     for i in os.listdir(os.getcwd()):50         if os.path.splitext(i)[1] == ‘.py‘:51             line = analyze_code(i)52             total_lines, total_comment_lines, total_blank_lines = total_lines + line[0], total_comment_lines + line[1], total_blank_lines + line[2]53 54     print "總程式碼數:", total_lines55     print "總注釋行數:", total_comment_lines, "占%0.2f%%" % (total_comment_lines*100.0/total_lines)56     print "總空行數:  ", total_blank_lines, "占%0.2f%%" % (total_blank_lines*100.0/total_lines)57 58 59 if __name__ == ‘__main__‘:60     run(FILE_PATH)

 

python 指令碼(擷取指定檔案夾、指定檔案格式、的程式碼數、注釋行數)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.