zoukankan      html  css  js  c++  java
  • 统计python文件中的代码,注释,空白对应的行数

    其实代码和空白行很好统计,难点是注释行

    python中的注释分为以#开头的单行注释

    或者以'''开头以'''结尾 或以"""开头以"""结尾的文档注释,如:

    '''

    hello world

    '''和

    '''

    hello world'''

    思路是用is_comment记录是否存在多行注释,如果不存在,则判断当前行是否以'''开头,是则将is_comment设为True,否则进行空行、当前行注释以及代码行的判断,如果is_comment已经为True即,多行注释已经开始,则判断当前行是否以'''结尾,是则将is_comment设为False,同时增加注释的行数。表示多行注释已经结束,反之继续,此时多行注释还未结束

    path = 'test.py'
    with open(path,'r',encoding='utf-8') as f:
        code_lines = 0       #代码行数
        comment_lines = 0    #注释行数
        blank_lines = 0      #空白行数  内容为'
    ',strip()后为''
        is_comment = False
        start_comment_index = 0 #记录以'''或"""开头的注释位置
        for index,line in enumerate(f,start=1):
            line = line.strip() #去除开头和结尾的空白符

     
        #判断多行注释是否已经开始  if not is_comment: if line.startswith("'''") or line.startswith('"""'): is_comment = True start_comment_index = index #单行注释 elif line.startswith('#'): comment_lines += 1 #空白行 elif line == '': blank_lines += 1 #代码行 else: code_lines += 1 #多行注释已经开始 else: if line.endswith("'''") or line.endswith('"""'): is_comment = False comment_lines += index - start_comment_index + 1 else: pass print("注释:%d" % comment_lines) print("空行:%d" % blank_lines) print("代码:%d" % code_lines)
  • 相关阅读:
    Smarty学习笔记(二)
    Smarty学习笔记(一)
    MVC学习笔记(一)
    2015羊年主流手机配置什么样?
    FPGA学习笔记(一)Verilog语法基础
    FPGA学习笔记(二)模块建立及变量连接
    STM32学习笔记(一)时钟和定时器
    Win8 HTML5与JS编程学习笔记(一)
    Win8 HTML5与JS编程学习笔记(二)
    LUOGU P2831 愤怒的小鸟 (NOIP 2016)
  • 原文地址:https://www.cnblogs.com/hupeng1234/p/6680230.html
Copyright © 2011-2022 走看看