|
发表于 2017-5-13 15:05:31
|
显示全部楼层
回帖奖励 +2 鱼币
- import easygui as g
- import os
- def show_result(start_dir):
- lines = 0
- total = 0
- text = ''
- for i in source_list:
- lines = source_list[i]
- total += lines
- text += "【%s】源文件%d个,源代码%d行\n" %( i,file_list[i],lines)
- title = '统计结果'
- msg = '您目前共累积编写了%d行代码,完成进度:%.2f %%\n离10w行代码还差%d行,请继续\\\
- 努力!' % (total, total/100000, 100000-total)
- g.textbox(msg,title,text)
- def calc_code(file_name):
- lines = 0
- with open(file_name,encoding = 'utf-8') as f:
- print('正在分析文件:%s.......'%file_name)
- try:
- for each_line in f:
- lines += 1
- except UnicodeDecodeError:
- pass #不可避免会遇到格式不兼容的文件,这里忽略。。。
- return lines
- def search_file(start_dir):
- os.chdir(start_dir) #改变工作目录
- for each_file in os.listdir(os.curdir):#列举当前工作目录文件名
- ext = os.path.splitext(each_file)[1]#得文件后缀名
- if ext in target:
- lines = calc_code(each_file) #调用计算行数文件
- #统计文件数
- try:
- file_list[ext] += 1
- except KeyError: #如果字典中不存在则抛出异常,添加字典减
- file_list[ext] = 1
- #统计源代码行数
- try:
- source_list[ext] += lines
- except KeyError:
- source_list[ext] = lines
- if os.path.isdir(each_file):
- search_file(each_file) #递归调用
- os.chdir(os.pardir)#递归调用后切记返回上一层目录
- target = ['.c',',cpp','.py','.cc','.java','.pas','.asm'] #源代码类型
- file_list = {}
- source_list = {}
- g.msgbox('请打开您存放所有代码的文件夹.......','统计代码量') #msgbox(msg,title)
- path = g.diropenbox('请选择您的代码库:')# 提供一个对话框,选择打开文件夹
- search_file(path)
- show_result(path)
复制代码
虽然程序是甲鱼大大写的,但是统计已经编写的代码行数很有成就感呢 |
|