1. 程式人生 > >Python小工具:統計程式碼行數

Python小工具:統計程式碼行數

本身程式碼難度不大,就是一個心血來潮做的小玩意

功能介紹

  1. 實現對於指定的字尾檔案進行行數統計
  2. 可以忽略指定的資料夾,對於一些IDE自動生成的程式碼可以進行忽略(預設忽略二進位制檔案)
  3. 對於檔案建立時間進行統計

Todo_List

  1. 把忽略資料夾的功能支援正則,現在的忽略功能有點僵硬
  2. 對於結果統計有更好的資料統計頁面,比如畫出一個餅圖或柱狀圖之類的

程式碼:

import os,sys,time
def get_year(now):
    filemt= time.localtime(os.stat(now).st_mtime) # 獲取檔案建立時間
    ModifiedTime=time.strftime("%Y-%m-%d",filemt)
    y=ModifiedTime[:4]
    return y
def count(path,suffix,ignore,statistics,years):
    cnt=0
    for fn in os.listdir(path):
        now = path+fn # 檔案路徑
        # print(fn)
        if os.path.isdir(now):
            # print(now+'\\')
            if now+'\\' in ignore:
                # print('ignore=',now+'\\')
                continue
            tmp,years=count(now+'\\',suffix,ignore,statistics,years)
            cnt = cnt + tmp
        else:
            filename,type=os.path.splitext(now)
            if type in suffix:
                # print(filename,type)
                try:
                    num = len(open(now, 'r').readlines())# 當前檔案的行數
                    y=get_year(now) # 獲取檔案建立時間(年)
                    # print(now,y)
                    years[y] = years[y]+num
                    statistics[type] = statistics.get(type,0) + num
                except UnicodeDecodeError:# 判斷二進位制檔案
                    pass
                else:
                    cnt = cnt + num
    return cnt,years
if __name__ == '__main__':
    ignore=['D:\\code\\python\\pygame\\pygame-samples-master\\',
            'D:\\code\\python\\Lo-runner-master\\',
            'D:\\code\\Django\\venv\\',
            'D:\\code\\eclipse-workspace\\',
            ]
    suffix=['.cpp','.c','.py','.java']
    years={'2016':0,'2017':0,'2018':0}
    src = 'D:\\code\\'
    statistics=dict()
    ans,years = count(src,suffix,ignore,statistics,years)
    print(src,'下總程式碼行數為:',ans)
    print('語言統計情況:')
    for key in statistics.keys():
        print(key,':',statistics[key])
    print('年份統計情況:')
    for key in years.keys():
        print(key,':',years[key])