搜索指定类型的代码文件并统计代码的行数

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 离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):
        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("请打开您存放所有代码的文件夹.......", "统计代码量")
path = g.diropenbox("请选择您的代码库:")    #返回绝对路径

search_file(path)
show_result(path)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值