|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
要求:
写一个程序统计你当前代码量的总和, 并显示离十万行代码量还有多远?
· 要求一: 递归搜索各个文件夹
要求二: 显示各个类型的源文件和源代码数量
· 要求三: 显示总行数与百分比
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】源文件 %s 个,源代码 %d 行\n' % (i,file_list[i],lines)
title = '统计结果'
msg = '您目前共累计编写了 %d 行代码,完成进度: %.2f %%\n 离 10 万 行代码还差%d行,请继续努力!' % (total,total/1000,100000-total)
g.textbox(msg, title, text)
def calc_code(file_name):
lines = 0
with open(file_name) 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): #listdir列举指定目录中的文件名,os.curdir指代当前目录
ext = os.path.splitext(each_file)[1] #分离文件名与扩展名,返回(f_name, f_extension)元组,[1]返回文件类型
if ext in target:
lines = calc_code(each_file) #统计行数
#还记得异常的用法吗?如果字典中不存,抛出KeyError,则添加字典键
#统计文件数目
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) #递归调用后切记住返回上一层目录 os.pardir
target = ['.c','.cpp','.py','.cc','.java','.pas','.asm']
file_list = {} #定义两个空字典
source_list = {}
g.msgbox('请打开您存放所有代码的文件夹......','统计代码量')
path = g.diropenbox('请选择您的代码库:') #返回用户选择的目录名
search_file(path)
show_result(path)
问题:
感觉这个程序对.py的文件免疫,其他文件类型统计正确,就.py的文件个数统计正确,代码行数统计错误~大神帮我看看~,谢啦
|
|