|
发表于 2025-4-4 14:06:20
|
显示全部楼层
代码问题分析及修正方案
这个代码存在以下几个主要问题:
1. target变量未初始化
原始代码:target =
修正后:target = ('.py', '.java', '.cpp') (示例扩展名,可根据需要修改)
2. 变量作用域问题
file_list和source_list应该使用global声明或在函数内初始化
3. 字典类型误用
file_list和source_list初始化为字典但被当作整数使用
修正后的完整代码:
- import easygui as g
- import os
- target = ('.py', '.txt') # 需要统计的文件扩展名
- file_count = 0
- total_lines = 0
- def show_result():
- global total_lines, file_count
- msg = f'共找到{file_count}个源代码文件,累计代码行数:{total_lines}行\n'
- msg += f'进度:{total_lines/1000:.2f}%,剩余目标:{100000 - total_lines}行'
- g.textbox(msg, "统计结果")
- def calc_code(filename):
- lines = 0
- try:
- with open(filename, 'r', encoding='utf-8') as f:
- for line in f:
- if line.strip(): # 跳过空行
- lines += 1
- except UnicodeDecodeError:
- return 0
- return lines
- def search_file(start_dir):
- global file_count, total_lines
- os.chdir(start_dir)
-
- for each_file in os.listdir():
- if os.path.splitext(each_file)[1] in target:
- lines = calc_code(each_file)
- if lines > 0:
- file_count += 1
- total_lines += lines
-
- if os.path.isdir(each_file):
- search_file(each_file)
- os.chdir(os.pardir)
- g.msgbox("请选择代码库目录", "代码统计")
- path = g.diropenbox("请选择目录:")
- if path:
- search_file(path)
- show_result()
复制代码
主要改进点:
1. 使用全局变量替代原来的字典结构
2. 添加文件编码处理(utf-8)
3. 优化空行过滤逻辑
4. 简化递归目录遍历逻辑
5. 添加路径有效性验证
这个版本应该可以正常运行,建议从简单的目录开始测试(目录中不要包含二进制文件)。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|