溫馨提示×

溫馨提示×

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

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

python如何實現代碼統計程序

發布時間:2021-04-06 10:31:11 來源:億速云 閱讀:280 作者:小新 欄目:開發技術

這篇文章將為大家詳細講解有關python如何實現代碼統計程序,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

# encoding="utf-8"

"""
統計代碼行數
"""

import sys
import os

def count_file_line(path):
 """統計文件的有效行數"""
 countLine = 0
 # 設置一個標志位,當遇到以"""或者'''開頭或者結尾的時候,置為False
 flag = True

 # 使用utf-8格式的編碼方式讀取文件,如果讀取失敗,將使用gbk編碼方式讀取文件
 try:
 fp = open(path, "r", encoding="utf-8")
 encoding_type = "utf-8"
 fp.close()
 except:
 encoding_type = "gbk"

 with open(path, "r", encoding=encoding_type) as fp:
 for line in fp:
  # 空行不統計
  if line.strip():
  line = line.strip()
  # 注意下面的這兩個elif必須要前面,這樣子當('"""')結束之后及時將flag置為True
  if line.endswith('"""') and flag == False:
   flag = True
   continue
  if line.endswith("'''") and flag == False:
   flag = True
   continue
  if flag == False:
   continue
  if line.startswith("#!") or line.startswith("#-*-") or line.startswith("# encoding"):
   countLine += 1
  # 如果以“#”號開頭的,不統計
  elif line.startswith("#"):
   continue
  # 如果同時以("'''")或者('"""')開頭或者結尾(比如:"""aaa"""),那么不統計
  elif line.startswith('"""') and line.endswith('"""') and line != '"""':
   continue
  elif line.startswith("'''") and line.endswith("'''") and line != "'''":
   continue
  # 如果以("'''")或者('"""')開頭或者結尾(比如:aaa"""或者"""bbb),那么不統計
  # 注意下面的這兩個elif必須要放后面
  elif line.startswith('"""') and flag == True:
   flag = False
   continue
  elif line.startswith("'''") and flag == True:
   flag = False
   continue
  else:
   countLine += 1
 return countLine

def count_codes(path,file_types=[]):
 """統計所有文件代碼行"""
 # 判斷path是目錄還是文件,如果是目錄的話,遍歷目錄下所有的文件
 if not os.path.exists(path):
 print("您輸入的路徑不存在!")
 return 0
 countTotalLine = 0
 file_paths = {}
 if os.path.isdir(path):
 for root,dirs,files in os.walk(path):
  for name in files:
  if not file_types:
   file_types = ["txt","py"]
   # print(file_types)
  if os.path.splitext(name)[1][1:] in file_types:
   file_path = os.path.normpath(os.path.join(root,name))
   # print(file_path)
   file_lines = count_file_line(file_path)
   countTotalLine += file_lines
   file_paths[file_path] = file_lines
 else:
 if not file_types:
  file_types = ["txt","py"]
 if os.path.splitext(path)[1][1:] in file_types:
  countTotalLine = count_file_line(path)
  file_paths[path] = count_file_line(path)

 return countTotalLine,file_paths


if __name__ == "__main__":
 # 打印出命令行輸入的參數
 # print(sys.argv)
 if len(sys.argv) < 2:
 print("請輸入路徑!")
 sys.exit()
 path = sys.argv[1]
 # print(path)
 file_types = sys.argv[2:]
 # print(file_types)
 print(count_codes(path,file_types))

關于“python如何實現代碼統計程序”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女