|

楼主 |
发表于 2020-7-26 23:36:58
|
显示全部楼层
- import easygui as g
- import os
- codingdict = {}
- typedict={}
- linecountdict={}
- def ChoiceCountType():
- '''选择要统计哪些代码文件类型'''
- global codingdict
- global typedict
- global linecountdict
- choices = [".py", ".c", ".cpp", ".txt",".cs",".aspx"] # 设置代码文件选项
- usertype = g.multchoicebox(msg="请从下列列表中选择要统计的代码文件类型!", title="代码统计", choices=choices)
- #codingdict = dict.fromkeys(usertype, [0, 0]) # 给类型字典赋初值 {类型,[个数,有效代码数]}
- typedict=dict.fromkeys(usertype,0)
- linecountdict=dict.fromkeys(usertype,0)
- dirpath = g.diropenbox()
- return dirpath
- def calc_code(paths,file_name):
- '''统计有效代码行的函数'''
- codinglines = 0
- with open(paths + "\" + file_name,errors="ignore") as fp:
- print('正在分析文件:%s ...' % file_name)
- dateline = fp.readlines()
- for line in dateline:
- if line == "\n":
- continue
- elif line.startswith("#"):
- continue
- else:
- codinglines+=1
- return codinglines
- def ChoiceDir(dirpath):
- '''用os.walk()遍历计算文件数量和有效代码数分别存进对应列表中'''
- global typedict
- global linecountdict
- for paths, dirs, files in os.walk(dirpath):
- if len(files) > 0: # 如果有文件,就执行下一步的遍历文件列表
- for file in files:
- ext = os.path.splitext(file)[1] # 切片出类型,然后判断出类型在不在编程类型文件里
- if ext in typedict.keys(): # 如果切出来的类型在字典的KEY中
- lines=calc_code(paths,file) #调用函数算出现在循环到的这个文件有多少有效代码行数
- typedict[ext]+=1 #基于这个key给typedict赋值,统计现在这个文件类型的文件数量
- linecountdict[ext]+=lines #基于这个key给linecountdict赋值,统计现在这个类型的文件有多少有效行数
- def ShowResult():
- msg=""
- text=""
- title="统计结果"
- totallines=0
- for i in linecountdict.keys():
- for each in typedict.keys():
- if i==each:
- text += (f"[{i}]类型的文件有{typedict[each]}个,共计有效代码量{linecountdict[i]}行\n")
- totallines+=linecountdict[i]
- #print(totallines)
- msg=f"您目前共累积编写了{totallines}行代码,完成进度:{float(totallines/10000)}%\n离 10 万行代码还差{10000-totallines}行,请继续努力!"
- g.textbox(msg, title, text)
- openpath = ChoiceCountType()
- ChoiceDir(openpath)
- ShowResult()
复制代码
老哥们,用两个字典存可以实现了,我想请教下,用一个带列表的字典- #codingdict = dict.fromkeys(usertype, [0, 0]) # 给类型字典赋初值 {类型,[个数,有效代码数]}
复制代码 然后遍历file时让个数和有效代码数自增有办法实现吗? |
|