前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python实现代码统计(代码+注释+空

Python实现代码统计(代码+注释+空

作者头像
py3study
发布2020-01-08 16:25:26
7220
发布2020-01-08 16:25:26
举报
文章被收录于专栏:python3python3
代码语言:javascript
复制
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 17 17:15:40 2014
@author: author
"""
import os;
path_head = '代码路径头部'
path_list = '代码绝对路径' 
fileClasses = ['java']   #需要统计的文件类型
totalLines = 0
commentAll = 0
normalAll = 0
whiteAll = 0
for root,dirs,files in os.walk(path_head + path_list):
    #处理路径中的 '/'
    dirLen = len(root)
    lastChar = root[dirLen-1:dirLen]
    if lastChar =='/' :
        root = root[0:dirLen-1]
         
    for afile in files:
        fileDir = root+'/'+ afile
             
        #过滤文件类型
        strs = afile.split('.')
        fileClass = strs[len(strs)-1]
        if fileClass not in fileClasses :
            continue
             
        with open(fileDir) as file:
            commentLines = 0
            whiteLines = 0
            normal = 0
            comment = False
                 
            lines = file.readlines()
            for i in lines:
                i = i.strip()
                #空行
                if(i==''):
                    whiteLines=whiteLines+1
                #注释 /*   */
                elif(i.startswith('/*') and True==i.endswith('*/')):
                    commentLines=commentLines+1
                #注释 /* 开头
                elif(i.startswith('/*') and False==i.endswith('*/')):
                    commentLines=commentLines+1
                    comment=True
                #注释 中间 和 */ 结尾
                elif(True==comment):
                    commentLines=commentLines+1
                    if(i.endswith('*/')):
                        comment=False
                #注释 //
                elif(i.startswith('//')):
                    commentLines=commentLines+1
                #代码
                else:
                    normal=normal+1
            #单文件统计结果
            print ('%s 代码行数:%d 空行数:%d 注释行数:%d'%(fileDir[len(path_head):], normal, whiteLines, commentLines))
            commentAll+= commentLines
            normalAll += normal
            whiteAll += whiteLines
#统计结果
print ('总行数:%d' %(commentAll + normalAll + whiteAll))
print ('总代码行数:%d' %(normalAll))
print ('总注释行数:%d' %(commentAll))
print ('总空行数:%d' %(whiteAll))

参考网上的代码修改而成,没有什么技术含量。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档