python实现代码统计程序


Posted in Python onSeptember 19, 2019

本文实例为大家分享了python实现代码统计程序的具体代码,供大家参考,具体内容如下

# encoding="utf-8"

"""
统计代码行数
"""

import sys
import os

def count_file_line(path):
 """统计文件的有效行数"""
 countLine = 0
 # 设置一个标志位,当遇到以"""或者'''开头或者结尾的时候,置为False
 flag = True

 # 使用utf-8格式的编码方式读取文件,如果读取失败,将使用gbk编码方式读取文件
 try:
 fp = open(path, "r", encoding="utf-8")
 encoding_type = "utf-8"
 fp.close()
 except:
 encoding_type = "gbk"

 with open(path, "r", encoding=encoding_type) as fp:
 for line in fp:
  # 空行不统计
  if line.strip():
  line = line.strip()
  # 注意下面的这两个elif必须要前面,这样子当('"""')结束之后及时将flag置为True
  if line.endswith('"""') and flag == False:
   flag = True
   continue
  if line.endswith("'''") and flag == False:
   flag = True
   continue
  if flag == False:
   continue
  if line.startswith("#!") or line.startswith("#-*-") or line.startswith("# encoding"):
   countLine += 1
  # 如果以“#”号开头的,不统计
  elif line.startswith("#"):
   continue
  # 如果同时以("'''")或者('"""')开头或者结尾(比如:"""aaa"""),那么不统计
  elif line.startswith('"""') and line.endswith('"""') and line != '"""':
   continue
  elif line.startswith("'''") and line.endswith("'''") and line != "'''":
   continue
  # 如果以("'''")或者('"""')开头或者结尾(比如:aaa"""或者"""bbb),那么不统计
  # 注意下面的这两个elif必须要放后面
  elif line.startswith('"""') and flag == True:
   flag = False
   continue
  elif line.startswith("'''") and flag == True:
   flag = False
   continue
  else:
   countLine += 1
 return countLine

def count_codes(path,file_types=[]):
 """统计所有文件代码行"""
 # 判断path是目录还是文件,如果是目录的话,遍历目录下所有的文件
 if not os.path.exists(path):
 print("您输入的路径不存在!")
 return 0
 countTotalLine = 0
 file_paths = {}
 if os.path.isdir(path):
 for root,dirs,files in os.walk(path):
  for name in files:
  if not file_types:
   file_types = ["txt","py"]
   # print(file_types)
  if os.path.splitext(name)[1][1:] in file_types:
   file_path = os.path.normpath(os.path.join(root,name))
   # print(file_path)
   file_lines = count_file_line(file_path)
   countTotalLine += file_lines
   file_paths[file_path] = file_lines
 else:
 if not file_types:
  file_types = ["txt","py"]
 if os.path.splitext(path)[1][1:] in file_types:
  countTotalLine = count_file_line(path)
  file_paths[path] = count_file_line(path)

 return countTotalLine,file_paths


if __name__ == "__main__":
 # 打印出命令行输入的参数
 # print(sys.argv)
 if len(sys.argv) < 2:
 print("请输入路径!")
 sys.exit()
 path = sys.argv[1]
 # print(path)
 file_types = sys.argv[2:]
 # print(file_types)
 print(count_codes(path,file_types))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python正则表达式中的括号匹配问题
Dec 14 Python
详细探究Python中的字典容器
Apr 14 Python
python中import学习备忘笔记
Jan 24 Python
机器学习经典算法-logistic回归代码详解
Dec 22 Python
python3处理含有中文的url方法
May 10 Python
python+opencv实现阈值分割
Dec 26 Python
使用Python和OpenCV检测图像中的物体并将物体裁剪下来
Oct 30 Python
python3实现单目标粒子群算法
Nov 14 Python
python+selenium定时爬取丁香园的新型冠状病毒数据并制作出类似的地图(部署到云服务器)
Feb 09 Python
Django实现从数据库中获取到的数据转换为dict
Mar 27 Python
python 实现aes256加密
Nov 27 Python
如何用PyPy让你的Python代码运行得更快
Dec 02 Python
python tkinter图形界面代码统计工具(更新)
Sep 18 #Python
python3获取url文件大小示例代码
Sep 18 #Python
弄懂这56个Python使用技巧(轻松掌握Python高效开发)
Sep 18 #Python
python3使用GUI统计代码量
Sep 18 #Python
django中的图片验证码功能
Sep 18 #Python
python tkinter图形界面代码统计工具
Sep 18 #Python
Python自动生成代码 使用tkinter图形化操作并生成代码框架
Sep 18 #Python
You might like
透析PHP的配置文件php.ini
2006/10/09 PHP
用PHP和ACCESS写聊天室(三)
2006/10/09 PHP
为PHP安装imagick时出现Cannot locate header file MagickWand.h错误的解决方法
2014/11/03 PHP
php页面,mysql数据库转utf-8乱码,utf-8编码问题总结
2015/08/27 PHP
php简单统计在线人数的方法
2016/05/10 PHP
PHP实现的mysql读写分离操作示例
2018/05/22 PHP
Laravel 实现Eloquent模型分组查询并返回每个分组的数量 groupBy()
2019/10/23 PHP
初学prototype,发个JS接受URL参数的代码
2006/09/25 Javascript
Prototype 学习 工具函数学习($w,$F方法)
2009/07/12 Javascript
JavaScript实现快速排序(自已编写)
2012/12/19 Javascript
关于jQuery object and DOM element
2013/04/15 Javascript
Chrome下ifame父窗口调用子窗口的问题示例探讨
2014/03/17 Javascript
jQuery打字效果实现方法(附demo源码下载)
2015/12/18 Javascript
js发送短信倒计时的简单实现方法
2016/09/08 Javascript
Angular2 父子组件数据通信实例
2017/06/22 Javascript
NodeJS实现图片上传代码(Express)
2017/06/30 NodeJs
js原生代码实现轮播图的实例讲解
2017/07/28 Javascript
详解Webpack多环境代码打包的方法
2018/08/03 Javascript
vue的.vue文件是怎么run起来的(vue-loader)
2018/12/10 Javascript
[04:44]显微镜下的DOTA2第二期——你所没有注意到的细节
2014/06/20 DOTA
[02:39]我与DAC之Newbee.Moogy:从论坛到TI
2018/03/26 DOTA
使用Python构建Hopfield网络的教程
2015/04/14 Python
python中__call__内置函数用法实例
2015/06/04 Python
Python爬取十篇新闻统计TF-IDF
2018/01/03 Python
对python中dict和json的区别详解
2018/12/18 Python
python__name__原理及用法详解
2019/11/02 Python
python飞机大战pygame游戏之敌机出场实现方法详解
2019/12/17 Python
pandas中read_csv的缺失值处理方式
2019/12/19 Python
python标准库OS模块函数列表与实例全解
2020/03/10 Python
win10安装python3.6的常见问题
2020/07/01 Python
CSS3实现自定义Checkbox特效实例代码
2017/04/24 HTML / CSS
德国旅游网站:weg.de
2018/06/03 全球购物
有趣的广告词
2014/03/18 职场文书
年终晚会活动方案
2014/08/21 职场文书
银行客户经理岗位职责
2015/04/09 职场文书
叶问观后感
2015/06/15 职场文书