Python學(xué)習(xí)教程:如何用Python統(tǒng)計(jì)代碼行數(shù)
Python學(xué)習(xí)教程:如何用python統(tǒng)計(jì)代碼行數(shù)
改良后的代碼可以對(duì)python和C系列的代碼實(shí)行行數(shù)計(jì)算,包括代碼、空行和注釋行,用re抓取注釋,傳入一個(gè)目錄自動(dòng)對(duì)其下的文件進(jìn)行讀取計(jì)算。
流程
首先判斷傳入?yún)?shù)是否為文件夾,不是則打印出提示,否則繼續(xù)(無(wú)返回),獲得目錄后,yongos.listdir對(duì)路徑下文件進(jìn)行遍歷,其中也包含文件夾,再次判斷是否為文件夾,是的話則遞歸調(diào)用此函數(shù),否則開(kāi)始執(zhí)行行數(shù)統(tǒng)計(jì),這里用os.path.join將路徑與文件名進(jìn)行拼接,方便之后直接傳給函數(shù),邏輯很簡(jiǎn)單,無(wú)非是執(zhí)行文件判斷,判斷是哪類文件,在調(diào)用對(duì)應(yīng)的注釋監(jiān)測(cè)正則代碼段進(jìn)行抓取,抓取到則行數(shù)+1,空白行也是一樣的原理,用strip(去除前后空格),然后行內(nèi)內(nèi)容為空則為空行,代碼段即為總行數(shù)減去其他兩類行數(shù),最后在外層將所有文件對(duì)應(yīng)的代碼段累加即為total。
關(guān)鍵
函數(shù)內(nèi)部是可以訪問(wèn)全局變量的,問(wèn)題在于函數(shù)內(nèi)部修改了變量,導(dǎo)致python認(rèn)為它是一個(gè)局部變量。
所以,如果在函數(shù)內(nèi)部訪問(wèn)并修改全局變量,應(yīng)該使用關(guān)鍵字 global 來(lái)修飾變量。
- import os
- import re
- #定義規(guī)則抓取文件中的python注釋
- re_obj_py = re.compile('[(#)]')
- #定義規(guī)則抓取文件中的C語(yǔ)言注釋
- re_obj_c = re.compile('[(//)(/*)(*)(*/)]')
- #判斷是否為python文件
- def is_py_file(filename):
- if os.path.splitext(filename)[1] == '.py':
- return True
- else:
- return False
- #判斷是否為c文件
- def is_c_file(filename):
- if os.path.splitext(filename)[1] in ['.c', '.cc', '.h']:
- return True
- else:
- return False
- #定義幾個(gè)全局變量用于計(jì)算所有文件總和(全部行數(shù)、代碼行數(shù)、空行數(shù)、注釋行數(shù))
- all_lines, code_lines, space_lines, comments_lines = 0, 0, 0, 0
- #判斷是否為文件夾,不是則輸出提示
- def count_codelines(dirpath):
- if not os.path.isdir(dirpath):
- print('input dir: %s is not legal!' % dirpath)
- return
- # 定義幾個(gè)全局變量用于計(jì)算每個(gè)文件行數(shù)(全部行數(shù)、代碼行數(shù)、空行數(shù)、注釋行數(shù))
- global all_lines, code_lines, space_lines, comments_lines
- #列出當(dāng)前文件夾下的文件(包含目錄)
- all_files = os.listdir(dirpath)
- for file in all_files:
- #將文件(目錄)名與路徑拼接
- file_name = os.path.join(dirpath, file)
- if os.path.isdir(file_name):
- count_codelines(file_name)
- else:
- temp_all_lines, temp_code_lines, temp_space_lines, temp_comments_lines = 0, 0, 0, 0
- f = open(file_name)
- for line in f:
- temp_all_lines += 1
- if line.strip() == '':
- temp_space_lines += 1
- continue
- if is_py_file(file_name) and re_obj_py.match(line.strip()):
- temp_comments_lines += 1
- if is_c_file(file_name) and re_obj_c.match(line.strip()):
- temp_comments_lines += 1
- temp_code_lines = temp_all_lines - temp_space_lines - temp_comments_lines
- print('%-15s : all_lines(%s)\t code_lines(%s)\t space_lines(%s)\t comments_lines(%s)'
- % (file, temp_all_lines, temp_code_lines, temp_space_lines, temp_comments_lines))
- all_lines += temp_all_lines
- code_lines += temp_code_lines
- space_lines += temp_space_lines
- comments_lines += temp_comments_lines
- if __name__ == '__main__':
- count_codelines('test')
- print('\n**** TOTAL COUNT ****\nall_lines = %s\ncode_lines = %s\nspace_lines = %s\ncomments_lines = %s' % (all_lines, code_lines, space_lines, comments_lines))
本期的Python學(xué)習(xí)教程先跟大家分享這么多!