|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
原帖地址:https://fishc.com.cn/thread-48359-1-1.html
题目要求:递归搜索用户所选文件夹下所有源文件,显示各个类型的源文件和源代码数量,用easygui模块的textbox()输出统计结果(总行数与百分比),如下图所示。
以下是小古比鱼编写的代码,使用了os.walk()递归搜索各文件夹,用len(f.read().split('\n'))统计各源文件代码行数,感觉比小甲鱼老师提供的参考答案更简洁、更优雅!望各位鱼友走过路过,留下宝贵意见,共同交流进步!
- import easygui as eg
- import os
- lib = eg.diropenbox('请选择您的代码库:','浏览文件夹')
- # 查找源文件
- Python_file = []
- C_file = []
- for each in os.walk(lib):
- for file in each[2]:
- if os.path.splitext(file)[1] == '.py':
- Python_file.append(os.path.join(each[0],file))
- elif os.path.splitext(file)[1] == '.cpp':
- C_file.append(os.path.join(each[0],file))
- # 统计代码量
- Python_code = 0
- C_code = 0
- for py in Python_file:
- with open(py,encoding='utf-8') as f:
- Python_code += len(f.read().split('\n'))
- for cpp in C_file:
- with open(cpp) as f:
- C_code += len(f.read().split('\n'))
- # 输出结果
- codes = Python_code + C_code
- result = f"您目前共累计编写了{codes}行代码,完成进度:{codes/100000:.2%}\n" \
- f"离10万行代码还差{100000-codes}行,请继续努力!"
- text = ""
- if Python_file:
- text += f"【.py】源文件{len(Python_file)}个,源代码{Python_code}行\n"
- if C_file:
- text += f"【.cpp】源文件{len(C_file)}个,源代码{C_code}行\n"
- eg.textbox(result,'统计结果',text)
- print(result,text,sep='\n')
复制代码 |
|