最新公告
  • 欢迎您光临站盟网(原知事网),一个优质的网站源码基地、精品网站模板和插件。欢迎加入永久SVIP
  • 使用python脚本统计当前根目录代码行数

    正文概述 知事网   2020-11-12 09:11   422

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

    主要思路

    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)t code_lines(%s)t space_lines(%s)t 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('n**** TOTAL COUNT ****nall_lines = %sncode_lines = %snspace_lines = %sncomments_lines = %s' % (all_lines, code_lines, space_lines, comments_lines))

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


    站盟网 » 使用python脚本统计当前根目录代码行数

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者
    请选择支付方式
    ×
    支付宝支付
    微信支付
    余额支付
    ×
    微信扫码支付 0 元