• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何使用python脚本统计当前根目录代码行数?

python 搞java代码 3年前 (2022-05-21) 35次浏览 已收录 0个评论

如果现在还是处于基础状态的小伙伴,一定要仔细阅读这篇内容,因为大家在最初学习的时候,都是要从几个方面入手的,基本上方面都是大同小异,还有一些内容是必学的,比如,像小编接下来给大家介绍的统计根目录代码行数,就是其中在试卷上经常能遇到的,因此,在最初不能潇洒写代码时候,我们就需要先把这些基础的内容掌握,这样才更好的发展哦~

主要思路

1、首先判断传入参数是否为文件夹

2、遍历文件

3、调用对应的注释监测正则代码段进行抓取

关键内容

函数内部是可以访问全局变量的,问题在于函数内部修改了变量,导致python认为它是一个局部变量。如果在函数内部访问并修改全局变量,应该使用关键字 global 来修饰变量。

实例代码演示

import os
import re
#定义规则抓取文件中的python注释
re_obj_py = re.compile('[(#)]')
#定义规则抓取文件中的C语言注释
re_obj_c = re.compile('[(//)(/*)(*)(*/)]')
#判断是否为python文件
def is_py_file(filename):
if os.path.splitext(filename)[1] == '.py':
return True
else:
return False
#判断是否为c文件
def is_c_file(filename):
if os.path.splitext(filename)[1] in ['.c', '.cc', '.h']:
return True
else:
return False
#定义几个全局变量用于计算所有文件总和(全部行数、代码行数、空行数、注释行数)
all_lines, code_lines, space_lines, comments_lines = 0, 0, 0, 0
#判断是否为文件夹,不是则输出提示
def count_codelines(dirpath):
if not os.path.isdir(dirpath):
print('input dir: %s is not legal!' % dirpath)
return
# 定义几个全局变量用于计算每个文件行数(全部行数、代码行数、空行数、注释行数)
global all_lines, code_lines, space_lines, comments_lines
#列出当前文件夹下的文件(包含目录)
all_files = os.listdir(dirpath)
for file in all_files:
#将文件(目录)名与路径拼接
file_name = os.path.join(dirpath, file)
if os.path.isdir(file_name):
count_codelines(file_name)
else:
temp_all_lines, temp_code_lines, temp_space_lines, temp_comments_lines = 0, 0, 0, 0
f = open(file_name)
for line in f:
temp_all_lines += 1
if line.strip() == '':
temp_space_lines += 1
continue
if is_py_file(file_name) and re_obj_py.match(line.strip()):
temp_comments_lines += 1
if is_c_file(file_name) and re_obj_c.match(line.strip()):
temp_comments_lines += 1
temp_code_lines = temp_all_lines - temp_space_lines - temp_comments_lines
print('%-15s : all_lines(%s)	 code_lines(%s)	 space_lines(%s)	 comments_lines(%s)'
% (file, temp_all_lines, temp_code_lines, temp_space_lines, temp_comments_lines))
all_lines += temp_all_lines
code_lines += temp_code_lines
space_lines += temp_space_lines
comments_lines += temp_comments_lines
if __name__ == '__main__':
count_codelines('test')
print('
**** TOTAL COUNT ****
all_lines = %s
code_lines = %s
space_lines = %s
comments_lines = %s' % (all_lines, code_lines, space_lines, comments_lines))

www#gaodaima.com来源gaodaimacom搞#^代%!码&网搞代码

大家如果在遇到统计行数问题,可以跟小编一样,利用上述的内容进行统计概述哦~或者直接套用都可以的,学习语言是一个不断累积的过程,大家如果不知道这个方法可以牢牢记住哦~

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何使用python脚本统计当前根目录代码行数?
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址