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)
  • 相关阅读:
    C语言数据结构(二)
    面向对象
    Java集合类汇总
    C语言运算符优先级和结合性
    c语言数据结构(一)
    浏览器间bug
    HTTP协议中的1xx,2xx,3xx,4xx,5xx状态码分别表示什么,列举常见错误码及含义
    SSL是啥?
    {转}大公司里怎样开发和部署前端代码?
    浏览器 HTTP 缓存原理分析
  • 原文地址:https://www.cnblogs.com/hupeng1234/p/6680230.html
Copyright © 2011-2022 走看看