项目要求
- 基本要求
- -c 统计文件字符数 (实现)
- -w 统计文件词数 (实现)
- -l 统计文件行数(实现)
- 扩展功能
- -s 递归处理目录下符合条件得文件(实现)
- -a 返回文件代码行 / 空行 / 注释行(实现)
- 高级功能
- -x 图形化界面(未实现)
解题思路
- 实现对文本的统计
- 读取文件
- 使用正则表达式处理文本内容
- 再实现拓展功能更复杂的统计及批量操作
- 用os模块获取文件以及判断是文件或目录
- 遍历目录下所有符合的文件
- 用sys模块实现在命令行解析参数
设计
- 将各个功能放在不同文件中
- recursive(list)
- wc(f, arg)
- str_count(name)
- line_count(name)
- 统计单词文件及模块:
- words_count(name)
- 统计代码行/空行/注释行文件及模块:
- codeCount.py:
- code_count(name)
流程图
代码说明
1. 遍历文件
def recursive(list):
f_list = os.listdir(list)
return f_list
2. 统计字符数
def str_count(name):
with open(name, 'r', encoding='UTF-8') as f:
n = 0
for line in f.readlines():
n += len(line)
return n
3. 统计行数
def line_count(name):
with open(name, 'r', encoding='UTF-8') as f:
n = 0
for line in f:
n += 1
return n
4. 统计单词数
import re
def words_count(name):
with open(name, 'r', encoding='UTF-8') as f:
n = 0
for line in f.readlines():
list_match = re.findall('[a-zA-Z]+', line.lower())
n += len(list_match)
return n
5. 统计空行/代码行/注释行数
def code_count(name):
with open(name, 'r', encoding='UTF-8') as f:
code_lines = 0
comm_lines = 0
space_lines = 0
for line in f.readlines():
if line.strip().startswith('#'):
comm_lines += 1
elif line.strip().startswith("'''") or line.strip().startswith('"""'):
comm_lines += 1
elif line.count('"""') == 1 or line.count("'''") == 1:
while True:
line = f.readline()
comm_lines += 1
if ("'''" in line) or ('"""' in line):
break
elif line.strip():
code_lines += 1
else:
space_lines += 1
return code_lines, comm_lines, space_lines
6. 命令行逻辑
def wc(f, arg):
if arg[1] == '-c':
str_num = str_count(f)
print(f + "文件字符数为: ", str_num)
elif arg[1] == '-w':
word_num = words_count(f)
print(f + "文件单词数为:", word_num)
elif arg[1] == '-l':
line_num = line_count(f)
print(f + "文件行数为:", line_num)
elif arg[1] == '-a':
code_lines_num, comm_lines_num, space_lines_num = code_count(f)
print(f + "文件代码行为:", code_lines_num)
print("注释行为:", comm_lines_num)
print("空行为:", space_lines_num)
测试运行
由于事先设置了工作路径所以默认路径与代码所在路径不同
- 基本模块测试
- 扩展模块测试
- 递归遍历文件夹下文件测试
- 文件名出错时
代码覆盖率
PSP
PSP2.1 | Personal Software Process Stages | 预估耗时(分钟) | 实际耗时(分钟) |
Planning | 计划 | 60 | 60 |
· Estimate | · 估计这个任务需要多少时间 | 60 | 60 |
Development | 开发 | 300 | 360 |
· Analysis | · 需求分析 (包括学习新技术) | 60 | 100 |
· Design Spec | · 生成设计文档 | 30 | 30 |
· Design Review | · 设计复审 (和同事审核设计文档) | 20 | 30 |
· Coding Standard | · 代码规范 (为目前的开发制定合适的规范) | 30 | 20 |
· Design | · 具体设计 | 30 | 30 |
· Coding | · 具体编码 | 240 | 300 |
· Code Review | · 代码复审 | 30 | 40 |
· Test | · 测试(自我测试,修改代码,提交修改) | 60 | 60 |
Reporting | 报告 | 20 | 30 |
· Test Report | · 测试报告 | 60 | 60 |
· Size Measurement | · 计算工作量 | 20 | 20 |
· Postmortem & Process Improvement Plan | · 事后总结, 并提出过程改进计划 | 20 | 30 |
合计 |
| 1040 | 1220 |
项目总结
以前写代码从没考虑过这么多,总是思考一阵之后便直接上手,遇到什么问题就查书查网上资料解决,突然想改就把之前写的模块推翻重来,因此也做了不少无用功,而且也很少总结,现在这样虽然工作量多了但是却感觉比以前开发要更快,少走了不少弯路,而且有写了博客后也感觉比之前掌握的更加扎实。