溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python如何統(tǒng)計指定目錄內(nèi)文件的代碼行數(shù)

發(fā)布時間:2021-08-07 14:00:47 來源:億速云 閱讀:116 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)python如何統(tǒng)計指定目錄內(nèi)文件的代碼行數(shù)的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

python統(tǒng)計指定目錄內(nèi)文件的代碼行數(shù),程序?qū)崿F(xiàn)統(tǒng)計指定目錄內(nèi)各個python文件的代碼總行數(shù),注釋行數(shù),空行數(shù),并算出所占百分比

這符合一些公司的小需求,實際代碼量的統(tǒng)計工作

效果如圖

python如何統(tǒng)計指定目錄內(nèi)文件的代碼行數(shù)

python如何統(tǒng)計指定目錄內(nèi)文件的代碼行數(shù)

代碼如下:

#coding:utf-8
import os,re
 
#代碼所在目錄
FILE_PATH = './'
 
def analyze_code(codefilesource):
  '''
  打開一個py文件,統(tǒng)計其中的代碼行數(shù),包括空行和注釋
  返回含該文件總行數(shù),注釋行數(shù),空行數(shù)的列表
  :param codefilesource:
  :return:
  '''
  total_line = 0
  comment_line = 0
  blank_line = 0
  with open(codefilesource,encoding='gb18030',errors='ignore') 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("代碼行數(shù):",total_line)
  print("注釋行數(shù):",comment_line,"占%0.2f%%"%(comment_line*100/total_line))
  print("空行數(shù):", blank_line, "占%0.2f%%"%(blank_line * 100 / total_line))
  return [total_line,comment_line,blank_line]
def run(FILE_PATH):
  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("總代碼行數(shù):",total_lines)
  print("總注釋行數(shù):",total_comment_lines,"占%0.2f%%"%(total_comment_lines*100/total_lines))
  print("總空行數(shù):", total_blank_lines, "占%0.2f%%"% (total_blank_lines * 100 / total_lines))
 
if __name__ == '__main__':
  run(FILE_PATH)

感謝各位的閱讀!關(guān)于“python如何統(tǒng)計指定目錄內(nèi)文件的代碼行數(shù)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI