from os import listdir
from os import sep
from os import getcwd
from os import path as opath
class CodeStatistic(object):
num_code = {}
code_state = {}
def __init__(self, *formats):
self.formats = formats
for temp_formate in formats:
self.__setattr__(temp_formate, 0)
self.__setattr__(temp_formate + "_has_gbk", False)
def statistic(self, cur_path):
if len(self.formats) == 0:
return
try:
base_dir = listdir(cur_path)
except Exception as e_reason:
print("讀取目錄失敗:", e_reason)
print("返回上一目錄繼續統計代碼量。。。")
return
for cur_file in base_dir:
file_abs_path = cur_path + sep + cur_file
if opath.isfile(file_abs_path):
cur_formate = cur_file.split(".")[-1]
if cur_formate in self.formats:
try:
temp_file = open(file_abs_path, encoding="utf-8")
except Exception as e_reason:
print("打開文件發生錯誤:", e_reason)
print("繼續讀取下一個文件。。。")
continue
while True:
try:
temp_line = temp_file.readline()
except UnicodeDecodeError:
temp_file = open(file_abs_path, encoding="gbk")
temp_line = temp_file.readline()
except Exception as e_reason:
print("读取文件发生未知错误:", e_reason)
return
if temp_line == "":
break
if temp_line.strip() != "":
self.__setattr__(cur_formate, self.__getattribute__(cur_formate)+1)
temp_file.close()
else:
self.statistic(cur_path + sep + cur_file)
if __name__ == "__main__":
print("傳說:知識是人類進步的階梯,那麼只有知識的人就會成為階梯")
print()
print("#"*30, "代碼量統計程序", "#"*30)
print("請輸入您要統計的格式后缀")
print("例如:c cpp java py")
while True:
lans = input("多個用【空格】分割,退出请输入exit,清除缓存数据请输入clear:")
if lans == "exit":
break
elif lans == "clear":
CodeStatistic.num_code = {}
print("清除缓存成功!!!")
continue
print("主人,貌似您寫的代碼有點多,小的馬上為您盘点一下。。。请稍等。。。")
will_deal_formate = lans.split()
for t_f in will_deal_formate[:]:
if t_f in CodeStatistic.num_code:
will_deal_formate.remove(t_f)
will_deal_formate = tuple(will_deal_formate)
statistic = CodeStatistic(*will_deal_formate)
try:
statistic.statistic(getcwd())
except Exception as reason:
print("主方法发生未知错误:", reason)
else:
# 缓存信息
for formatx in will_deal_formate:
CodeStatistic.num_code[formatx] = statistic.__getattribute__(formatx)
CodeStatistic.code_state[formatx + "_has_gbk"] = statistic.__getattribute__(formatx + "_has_gbk")
# 输出缓存信息
keys = CodeStatistic.num_code.keys()
for key in keys:
print(key, ":", CodeStatistic.num_code[key])
if CodeStatistic.code_state[key + "_has_gbk"]:
print("提示:主人,您的", key, "代码有点老了哦,竟然有 GBK 编码的文件!!!")
print()
代碼量統計程序
最新推荐文章于 2021-02-21 10:37:42 发布