python实现统计代码行数的方法

本文实例讲述了python实现统计代码行数的方法。分享给大家供大家参考。具体实现方法如下:

'''
Author: liupengfei
Function: count lines of code in a folder iteratively
Shell-format: cmd [dir]
Attention: default file encode is utf8 and default file type is java-source-file. But users can customize this script by just modifing global variables.
'''
import sys
import os
import codecs
from _pyio import open
totalCount = 0;
fileType = '.java'
descLineBegin = '//'
descBlockBegin = r'/**'
descBlockEnd = r'*/'
fileEncode = 'utf-8'
def main():
  DIR = os.getcwd()
  if len(sys.argv) >= 2:
    DIR = sys.argv[1]
  if os.path.exists(DIR) and os.path.isdir(DIR):
    print('target directory is %s' % DIR)
    countDir(DIR)
    print('total code line is %d' % totalCount)
  else:
    print('target should be a directory!')
def isFileType(file):
  return len(fileType) + file.find(fileType) == len(file)
def countDir(DIR):
  for file in os.listdir(DIR):
    absPath = DIR + os.path.sep + file;
    if os.path.exists(absPath):
      if os.path.isdir(absPath):
        countDir(absPath)
      elif isFileType(absPath):
        try:
          countFile(absPath)
        except UnicodeDecodeError:
          print(
            '''encode of %s is different, which
is not supported in this version!'''
            )
def countFile(file):
  global totalCount
  localCount = 0
  isInBlockNow = False
  f = codecs.open(file, 'r', fileEncode);
  for line in f:
    if (not isInBlockNow) and line.find(descLineBegin) == 0:
      pass;
    elif (not isInBlockNow) and line.find(descBlockBegin) >= 0:
      if line.find(descBlockBegin) > 0:
        localCount += 1
      isInBlockNow = True;
    elif isInBlockNow and line.find(descBlockEnd) >= 0:
      if line.find(descBlockEnd) + len(descBlockEnd) < len(line):
        localCount += 1
      isInBlockNow = False;
    elif (not isInBlockNow) and len(line.replace('\\s+', '')) > 0:
      localCount += 1
  f.close()
  totalCount += localCount
  print('%s : %d' % (file, localCount))
if __name__ == '__main__':
  main();

希望本文所述对大家的Python程序设计有所帮助。

(0)

相关推荐

  • Python3读取UTF-8文件及统计文件行数的方法

    本文实例讲述了Python3读取UTF-8文件及统计文件行数的方法.分享给大家供大家参考.具体实现方法如下: ''''' Created on Dec 21, 2012 Python 读取UTF-8文件 统计文件的行数目 @author: liury_lab ''' # -*- coding: utf-8 -*- import codecs # 对较小的文件,最简单的方法是将文件读入一个行列表中, # 然后计算列表的长度即可 count = len(codecs.open('d:/FreakOu

  • python实现代码行数统计示例分享

    复制代码 代码如下: #!/usr/bin/python '''        File      : count.py        Author    : Mike        E-Mail    : Mike_Zhang@live.com'''import sys,os extens = [".c",".cpp",".hpp",".h"]linesCount = 0filesCount = 0 def funCount

  • python统计一个文本中重复行数的方法

    本文实例讲述了python统计一个文本中重复行数的方法.分享给大家供大家参考.具体实现方法如下: 比如有下面一个文件 2 3 1 2 我们期望得到 2,2 3,1 1,1 解决问题的思路: 出现的文本作为key, 出现的数目作为value,然后按照value排除后输出 最好按照value从大到小输出出来,可以参照: 复制代码 代码如下: in recent Python 2.7, we have new OrderedDict type, which remembers the order in

  • python 统计代码行数简单实例

     python 统计代码行数简单实例 送测的时候,发现需要统计代码行数 于是写了个小程序统计自己的代码的行数. #calclate_code_lines.py import os def afileline(f_path): res = 0 f = open(f_path) for lines in f: if lines.split(): res += 1 return res if __name__=='__main__': host = 'E:'+os.sep+'develop'+os.s

  • 使用python统计文件行数示例分享

    复制代码 代码如下: import time def block(file,size=65536):    while True:        nb = file.read(size)        if not nb:           break        yield nb def getLineCount(filename):    with open(filename,"r",encoding="utf-8") as f:        return

  • Python实现对excel文件列表值进行统计的方法

    本文实例讲述了Python实现对excel文件列表值进行统计的方法.分享给大家供大家参考.具体如下: #!/usr/bin/env python #coding=gbk #此PY用来统计一个execl文件中的特定一列的值的分类 import win32com.client filename=raw_input("请输入要统计文件的详细地址:") flag=0 #用于判断文件 名如果不带'日'就为 0 if '\xc8\xd5' in filename:flag=1 print 50*'

  • Python脚本实现代码行数统计代码分享

    之前用bash实现过(http://www.jb51.net/article/61943.htm),不过那个不能在windows下使用,所以就写了个python版,也方便我以后使用--这里就不多介绍了,不懂的google下. 实现代码 复制代码 代码如下: #!/usr/bin/python '''         File      : count.py         Author    : Mike         E-Mail    : Mike_Zhang@live.com ''' i

  • Python中统计函数运行耗时的方法

    本文实例讲述了Python中统计函数运行耗时的方法.分享给大家供大家参考.具体实现方法如下: import time def time_me(fn): def _wrapper(*args, **kwargs): start = time.clock() fn(*args, **kwargs) print "%s cost %s second"%(fn.__name__, time.clock() - start) return _wrapper #这个装饰器可以在方便地统计函数运行的

  • Python实现统计代码行的方法分析

    本文实例讲述了Python实现统计代码行的方法.分享给大家供大家参考,具体如下: 参加光荣之路测试开发班已三月有余,吴总上课也总问" 咱们的课上了这么多次了大家实践了多少行代码了?".这里是一个一脸懵逼的表情.该怎么统计呢?一个个文件数当然不可取,能用代码解决的事咱们坚决不动手.最近在网上刷题时也正好遇到有这么一道题,所以决定撸一撸. 题目:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码.包括空行和注释,但是要分别列出来. 首先分析一下思路捋一下大象装冰箱的步骤,从一个给定

  • python实现统计代码行数的方法

    本文实例讲述了python实现统计代码行数的方法.分享给大家供大家参考.具体实现方法如下: ''' Author: liupengfei Function: count lines of code in a folder iteratively Shell-format: cmd [dir] Attention: default file encode is utf8 and default file type is java-source-file. But users can customi

  • Intellij idea使用Statistic统计代码行数的方法

    一.安装Statistic 1.打开IDEA 2.打开settings进行设置 3.选择plugins,进行插件安装 4.搜索Statistic并安装 5.下载完成之后,重启IDEA,此时Statistic就安装好了 二.使用Statistic 1.安装好Statistic之后我们可以通过以下步骤 将Statistic插件的控制台展示出来 view -> Tool Windows -> Statistic 2.我们可以选中我们想统计的服务来计算java代码或者配置文件行数 三.遇到的问题 使用

  • python实现统计代码行数的小工具

    一个用python实现的统计代码行数的小工具,供大家参考,具体内容如下 实现功能 计算出某一目录以及子目录下代码文件的行数 在计算代码的过程中,只对标准命名的文件进行统计,如[文件名.文件类型] 排除了以"#"开头的包含文件,宏定义等,如#include, #define, #pragma等 排除了c,cpp文件中的"//", "/-/"等的注释 排除了python文件中import, from 等开头的导入 使用方法 新建countLines.

  • C#统计C、C++及C#程序代码行数的方法

    本文实例讲述了C#统计C.C++及C#程序代码行数的方法.分享给大家供大家参考.具体如下: 本文中的两个函数 1)用于统计扩展名为 .h .c .cpp .cs 文件的代码行数 public static int LinesOfCode(string filename) 2)用于递归统计一个文件夹内所有扩展名为 .h .c .cpp .cs 文件的代码行数 public static int LinesOfFolder(string foldername) 一.什么样的情况算一行代码 需要注意如

  • 在.NET中取得代码行数的方法

    文章目的 介绍在.NET中取得代码行数的方法 代码 复制代码 代码如下: [STAThread] static void Main(string[] args) { ReportError("Yay!"); } static private void ReportError(string Message) { StackFrame CallStack = new StackFrame(1, true); Console.Write("Error: " + Messa

  • PHP实现统计代码行数小工具

    本文实例为大家分享了PHP实现统计代码行数小工具,供大家参考,具体内容如下 为了方面统计编程代码行数,做了一个小工具. 自动统计指定目录以及目录下的所有文件. <?php class TotalCode { /** * 统计当前文件有多少行代码, * @return TotalCodeInfo */ public function totalByFile($fullFileName) { $fileContent = file_get_contents($fullFileName); $line

  • PHP统计代码行数的小代码

    本文实例为大家分享了PHP统计代码行数的具体代码,供大家参考,具体内容如下 想统计一下项目中一共有多少行代码,结果没找到什么好的工具,就自己写了一个. 效率不怎么样. <?php /** * Created by PhpStorm. * User: luyanfeng * Date: 16/7/12 * Time: 下午1:45 */ /** * @param $dir * @return int */ function countLine($dir) { $count = 0; if (is_

随机推荐