使用Python设计一个代码统计工具


Posted in Python onApril 04, 2018

问题

设计一个程序,用于统计一个项目中的代码行数,包括文件个数,代码行数,注释行数,空行行数。尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目,例如:

# type用于指定文件类型
python counter.py --type python

输出:

files:10
code_lines:200
comments:100
blanks:20

分析

这是一个看起来很简单,但做起来有点复杂的设计题,我们可以把问题化小,只要能正确统计一个文件的代码行数,那么统计一个目录也不成问题,其中最复杂的就是关于多行注释,以 Python 为例,注释代码行有如下几种情况:

1、井号开头的单行注释

# 单行注释

2、多行注释符在同一行的情况

"""这是多行注释"""
'''这也是多行注释'''
3、多行注释符

"""
这3行都是注释符
"""

我们的思路采取逐行解析的方式,多行注释需要一个额外的标识符in_multi_comment 来标识当前行是不是处于多行注释符当中,默认为 False,多行注释开始时,置为 True,遇到下一个多行注释符时置为 False。从多行注释开始符号直到下一个结束符号之间的代码都应该属于注释行。

知识点

如何正确读取文件,读出的文件当字符串处理时,字符串的常用方法

简化版

我们逐步进行迭代,先实现一个简化版程序,只统计Python代码的单文件,而且不考虑多行注释的情况,这是任何入门 Python 的人都能实现的功能。关键地方是把每一行读出来之后,先用 strip() 方法把字符串两边的空格、回车去掉

# -*- coding: utf-8 -*-
"""
只能统计单行注释的py文件
"""
def parse(path):
 comments = 0
 blanks = 0
 codes = 0
 with open(path, encoding='utf-8') as f:
 for line in f.readlines():
  line = line.strip()
  if line == "":
  blanks += 1
  elif line.startswith("#"):
  comments += 1
  else:
  codes += 1
 return {"comments": comments, "blanks": blanks, "codes": codes}
if __name__ == '__main__':
 print(parse("xxx.py"))

多行注释版

如果只能统计单行注释的代码,意义并不大,要解决多行注释的统计才能算是一个真正的代码统计器

# -*- coding: utf-8 -*-
"""

可以统计包含有多行注释的py文件

"""
def parse(path):
 in_multi_comment = False # 多行注释符标识符号
 comments = 0
 blanks = 0
 codes = 0
 with open(path, encoding="utf-8") as f:
 for line in f.readlines():
  line = line.strip()
  # 多行注释中的空行当做注释处理
  if line == "" and not in_multi_comment:
  blanks += 1
  # 注释有4种
  # 1. # 井号开头的单行注释
  # 2. 多行注释符在同一行的情况
  # 3. 多行注释符之间的行
  elif line.startswith("#") or \
    (line.startswith('"""') and line.endswith('"""') and len(line)) > 3 or \
   (line.startswith("'''") and line.endswith("'''") and len(line) > 3) or \
   (in_multi_comment and not (line.startswith('"""') or line.startswith("'''"))):
  comments += 1
  # 4. 多行注释符的开始行和结束行
  elif line.startswith('"""') or line.startswith("'''"):
  in_multi_comment = not in_multi_comment
  comments += 1
  else:
  codes += 1
 return {"comments": comments, "blanks": blanks, "codes": codes}
if __name__ == '__main__':
 print(parse("xxx.py"))

上面的第4种情况,遇到多行注释符号时,in_multi_comment 标识符进行取反操作是关键操作,而不是单纯地置为 False 或 True,第一次遇到 """ 时为True,第二次遇到 """ 就是多行注释的结束符,取反为False,以此类推,第三次又是开始,取反又是True。

那么判断其它语言是不是要重新写一个解析函数呢?如果你仔细观察的话,多行注释的4种情况可以抽象出4个判断条件,因为大部分语言都有单行注释,多行注释,只是他们的符号不一样而已。

CONF = {"py": {"start_comment": ['"""', "'''"], "end_comment": ['"""', "'''"], "single": "#"},
 "java": {"start_comment": ["/*"], "end_comment": ["*/"], "single": "//"}}
start_comment = CONF.get(exstansion).get("start_comment")
end_comment = CONF.get(exstansion).get("end_comment")
cond2 = False
cond3 = False
cond4 = False
for index, item in enumerate(start_comment):
 cond2 = line.startswith(item) and line.endswith(end_comment[index]) and len(line) > len(item)
 if cond2:
 break
for item in end_comment:
 if line.startswith(item):
 cond3 = True
 break
for item in start_comment+end_comment:
 if line.startswith(item):
 cond4 = True
 break
if line == "" and not in_multi_comment:
 blanks += 1
# 注释有4种
# 1. # 井号开头的单行注释
# 2. 多行注释符在同一行的情况
# 3. 多行注释符之间的行
elif line.startswith(CONF.get(exstansion).get("single")) or cond2 or \
 (in_multi_comment and not cond3):
 comments += 1
# 4. 多行注释符分布在多行时,开始行和结束行
elif cond4:
 in_multi_comment = not in_multi_comment
 comments += 1
else:
 codes += 1

只需要一个配置常量把所有语言的单行、多行注释的符号标记出来,对应出 cond1到cond4几种情况就ok。剩下的任务就是解析多个文件,可以用 os.walk 方法。

def counter(path):
 """
 可以统计目录或者某个文件
 :param path:
 :return:
 """
 if os.path.isdir(path):
 comments, blanks, codes = 0, 0, 0
 list_dirs = os.walk(path)
 for root, dirs, files in list_dirs:
  for f in files:
  file_path = os.path.join(root, f)
  stats = parse(file_path)
  comments += stats.get("comments")
  blanks += stats.get("blanks")
  codes += stats.get("codes")
 return {"comments": comments, "blanks": blanks, "codes": codes}
 else:
 return parse(path)

当然,想要把这个程序做完善,还有很多工作要多,包括命令行解析,根据指定参数只解析某一种语言。

补充:

Python实现代码行数统计工具

我们经常想要统计项目的代码行数,但是如果想统计功能比较完善可能就不是那么简单了, 今天我们来看一下如何用python来实现一个代码行统计工具。

思路:

首先获取所有文件,然后统计每个文件中代码的行数,最后将行数相加.

实现的功能:

统计每个文件的行数;
统计总行数;
统计运行时间;
支持指定统计文件类型,排除不想统计的文件类型;
递归统计文件夹下包括子文件件下的文件的行数;

排除空行;

# coding=utf-8
import os
import time
basedir = '/root/script'
filelists = []
# 指定想要统计的文件类型
whitelist = ['php', 'py']
#遍历文件, 递归遍历文件夹中的所有
def getFile(basedir):
 global filelists
 for parent,dirnames,filenames in os.walk(basedir):
  #for dirname in dirnames:
  # getFile(os.path.join(parent,dirname)) #递归
  for filename in filenames:
   ext = filename.split('.')[-1]
   #只统计指定的文件类型,略过一些log和cache文件
   if ext in whitelist:
    filelists.append(os.path.join(parent,filename))
#统计一个文件的行数
def countLine(fname):
 count = 0
 for file_line in open(fname).xreadlines():
  if file_line != '' and file_line != '\n': #过滤掉空行
   count += 1
 print fname + '----' , count
 return count
if __name__ == '__main__' :
 startTime = time.clock()
 getFile(basedir)
 totalline = 0
 for filelist in filelists:
  totalline = totalline + countLine(filelist)
 print 'total lines:',totalline
 print 'Done! Cost Time: %0.2f second' % (time.clock() - startTime)

结果:

[root@pythontab script]# python countCodeLine.py
/root/script/test/gametest.php---- 16
/root/script/smtp.php---- 284
/root/script/gametest.php---- 16
/root/script/countCodeLine.py---- 33
/root/script/sendmail.php---- 17
/root/script/test/gametest.php---- 16
total lines: 382
Done! Cost Time: 0.00 second
[root@pythontab script]#

只会统计php和python文件,非常方便。

总结

以上所述是小编给大家介绍的使用Python设计一个代码统计工具,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python获取糗百图片代码实例
Dec 18 Python
使用Python获取CPU、内存和硬盘等windowns系统信息的2个例子
Apr 15 Python
Python常用正则表达式符号浅析
Aug 13 Python
Python 迭代器与生成器实例详解
May 18 Python
Python简单实现控制电脑的方法
Jan 22 Python
Python 实现还原已撤回的微信消息
Jun 18 Python
Python3 sys.argv[ ]用法详解
Oct 24 Python
Centos7 下安装最新的python3.8
Oct 28 Python
Python下利用BeautifulSoup解析HTML的实现
Jan 17 Python
Python表达式的优先级详解
Feb 18 Python
python3 自动打印出最新版本执行的mysql2redis实例
Apr 09 Python
浅谈Python数学建模之数据导入
Jun 23 Python
用 Python 连接 MySQL 的几种方式详解
Apr 04 #Python
Python基于辗转相除法求解最大公约数的方法示例
Apr 04 #Python
对numpy中数组元素的统一赋值实例
Apr 04 #Python
Python 元类实例解析
Apr 04 #Python
对numpy 数组和矩阵的乘法的进一步理解
Apr 04 #Python
Numpy数组的保存与读取方法
Apr 04 #Python
基于Python Numpy的数组array和矩阵matrix详解
Apr 04 #Python
You might like
ajax+php打造进度条代码[readyState各状态说明]
2010/04/12 PHP
深入理解ob_flush和flush的区别(ob_flush()与flush()使用方法)
2013/02/06 PHP
php使用PDO执行SQL语句的方法分析
2017/02/16 PHP
原生javascript实现Tab选项卡切换功能
2015/01/12 Javascript
JavaScript生成随机字符串的方法
2015/03/19 Javascript
Css3制作变形与动画效果
2015/07/24 Javascript
javascript实现的上下无缝滚动效果
2016/09/19 Javascript
微信小程序 选择器(时间,日期,地区)实例详解
2016/11/16 Javascript
Bootstrap弹出框modal上层的输入框不能获得焦点问题的解决方法
2016/12/13 Javascript
JS异步文件分片断点上传的实现思路
2016/12/25 Javascript
jQuery实现图片滑动效果
2017/03/08 Javascript
详解Vue2+Echarts实现多种图表数据可视化Dashboard(附源码)
2017/03/21 Javascript
浅谈React Native 中组件的生命周期
2017/09/08 Javascript
Thinkjs3新手入门之添加一个新的页面
2017/12/06 Javascript
[57:47]Fnatic vs Winstrike 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
python 系统调用的实例详解
2017/07/11 Python
Ubuntu安装Jupyter Notebook教程
2017/10/18 Python
python使用selenium登录QQ邮箱(附带滑动解锁)
2019/01/23 Python
Python 使用list和tuple+条件判断详解
2019/07/30 Python
详细介绍pandas的DataFrame的append方法使用
2019/07/31 Python
使用浏览器访问python写的服务器程序
2019/10/10 Python
关于windows下Tensorflow和pytorch安装教程
2020/02/04 Python
基于python3实现倒叙字符串
2020/02/18 Python
python图片剪裁代码(图片按四个点坐标剪裁)
2020/03/10 Python
Python2及Python3如何实现兼容切换
2020/09/01 Python
解决python3输入的坑——input()
2020/12/05 Python
台湾菁英交友:结识黄金单身的台湾人
2018/01/22 全球购物
北京-环亚运商测试题.net程序员初步测试题
2013/05/28 面试题
Python里面如何实现tuple和list的转换
2012/06/13 面试题
出纳试用期自我鉴定范文
2014/09/16 职场文书
黄石寨导游词
2015/02/05 职场文书
伏羲庙导游词
2015/02/09 职场文书
项目技术负责人岗位职责
2015/04/13 职场文书
2015年化妆品销售工作总结
2015/05/11 职场文书
浅谈MySQL表空间回收的正确姿势
2021/10/05 MySQL
讨论nginx location 顺序问题
2022/05/30 Servers