题目

有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。

代码

参照网络上代码

# coding: utf-8
import os
import re # 代码所在目录
FILE_PATH = 'TestDir' def count_line(file):
note_line = 0 # 注释行数
blank_line = 0 # 空行
with open(file, 'r', encoding='utf-8') as f:
lines = f.readlines()
total_line = len(lines) # 代码总行数
line_index = 0
# 遍历每一行
while line_index < total_line:
line = lines[line_index]
# 检查是否为注释
if line.startswith("#"):
note_line += 1
elif re.match(r"\s*'''", line) is not None:
note_line += 1
while re.match(".*'''$", line) is None:
line = lines[line_index]
note_line += 1
line_index += 1
# 检查是否为空行
elif line == "\n":
blank_line += 1
line_index += 1
print("====================================================")
print(" 在文件%s中:" % file)
print("----------------------------------------------------")
print("代码总行数:", total_line)
print("注释行数:", note_line, "占%0.2f%%" % (note_line * 100 / total_line))
print("空行数: ", blank_line, "占%0.2f%%" % (blank_line * 100 / total_line))
return [total_line, note_line, blank_line] def run(file_path):
# 切换到code所在目录
os.chdir(file_path)
# 遍历该目录下的py文件
total_lines = 0
total_note_lines = 0
total_blank_lines = 0
for i in os.listdir(os.getcwd()):
if os.path.splitext(i)[1] == '.py':
line = count_line(i)
total_lines = total_lines + line[0]
total_note_lines = total_note_lines + line[1]
total_blank_lines = total_blank_lines + line[2]
print("==================================================")
print("总代码行数:", total_lines)
print("总注释行数:", total_note_lines, "占%0.2f%%" % (total_note_lines * 100 / total_lines))
print("总空行数: ", total_blank_lines, "占%0.2f%%" % (total_blank_lines * 100 / total_lines)) if __name__ == '__main__':
run(FILE_PATH)

最新文章

  1. runtime 初入
  2. AI (Adobe Illustrator)详细用法(四)
  3. Doctrine2 SQL语句
  4. js常见执行方法$(document).load(),$(document).ready()
  5. HDU 1422 重温世界杯
  6. HD1064Financial Management
  7. table_open_cache
  8. 20个2014年最优秀的PHP框架
  9. A题笔记(6)
  10. 随意记的一点 js 笔记
  11. hadoop 2.2.0集群安装
  12. mysql 安装错误 解决方法
  13. super函数没有那么简单-super原理剖析
  14. Android Studio精彩案例(一)《ActionBar和 ViewPager版仿网易新闻客户端》
  15. objectLiteral.js
  16. Linux应急响应(二):捕捉短连接
  17. MongoDB中设置expire过期自动删除
  18. 作业一 031502140 博客地址yeze651521
  19. solaris之cpu
  20. 强化学习使用pygame模块的安装

热门文章

  1. php面试专题---2、常量及数据类型考点
  2. 51单片机的idata,xdata,pdata,data的详解
  3. Dealing with exceptions thrown in Application_Start()
  4. xshell链接linux出现SSH服务器拒绝了密码 的解决方案
  5. 公司-IT-Mercari:Mercari 百科
  6. Php单元测试 phpunit & codecept
  7. Ubuntu安装护眼程序
  8. 插件化框架解读之Android 资源加载机制详解(二)
  9. 面相对象编程 扩充之封装、访问机制、 property
  10. top查看进程的参数