littlefishgan 发表于 2020-6-3 22:25:09

easygui 最后一题求助

照着小甲鱼代码打了一遍,统计结果居然是0{:10_266:}
代码如下
import easygui as g
import os

def show_result(start_dir):
    lines = 0
    total = 0
    text = ''

    for i in source_list:
      lines = source_list
      total += lines
      text +='【%s】源文件 %d 个,源代码 %d 行\n'% (i,file_list,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,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)
      if ext in target:
            lines = calc_code(each_file)#统计行数
            #统计文件数
            try:
                file_list += 1
            except KeyError:
                file_list = 1
            #统计源代码行数
            try:
                source_list += lines
            except KeyError:
                source_list = lines #如果字典里没有就添加一个

      if os.path.isdir(each_file):
            search_file(each_file) #递归调用
            os.chdir(os.pardir)#返回上一层目录




target = ['.c','.cop',',py','.cc','.java','.pas','.asm']
file_list = {}
source_list = {}

g.msgbox('请打开您存放所有代码的文件夹......','统计代码量')
path = g.diropenbox("请选择您的代码库:")

search_file(path)
show_result(path)


D:\统计结果.png

txxcat 发表于 2020-6-4 00:45:08

我猜你的代码只有py文件,如果有了其他的代码,C呀,java呀,结果就会好一点,因为你的target里面并没有'.py',target = ['.c','.cop',',py','.cc','.java','.pas','.asm']

txxcat 发表于 2020-6-4 00:52:43

再有,遍历文件不要在用复杂的递归了,用一个os.walk方便N倍,参考之前写的作业:
import easygui as g
import os
ext=['.py','.c', '.cpp', '.cc', '.java', '.pas', '.asm']
dn=g.diropenbox(msg='请选择需要统计的文件夹',title='代码统计',default=None)
line=0
count=0
if dn!=None:
    for i in os.walk(dn):
      os.chdir(i)
      for j in i:
            extname=os.path.splitext(j)
            if extname.lower() in ext:
                print('正在分析文件:%s ...' % j)
                count+=1
                try:
                  with open(j,encoding='utf-8') as fa:
                        for eachline in fa:
                            line+=1
                except (OSError,UnicodeDecodeError) as reason:
                  print(j,'发生错误!'+str(reason))
    g.msgbox(('一共%d个文件,合计%d条代码!' % (count,line)))

littlefishgan 发表于 2020-6-4 13:11:11

txxcat 发表于 2020-6-4 00:45
我猜你的代码只有py文件,如果有了其他的代码,C呀,java呀,结果就会好一点,因为你的target里面并没有'.p ...

感谢,居然是那个逗号的问题{:10_285:}
页: [1]
查看完整版本: easygui 最后一题求助