Python統(tǒng)計python文件中代碼,注釋及空白對應的行數示例【測試可用】
本文實例講述了Python實現(xiàn)統(tǒng)計python文件中代碼,注釋及空白對應的行數。分享給大家供大家參考,具體如下:
其實代碼和空白行很好統(tǒng)計,難點是注釋行
python中的注釋分為以#開頭的單行注釋
或者以'''開頭以'''結尾 或以"""開頭以"""結尾的文檔注釋,如:
''' hello world '''
和
''' hello world'''
思路是用is_comment
記錄是否存在多行注釋,如果不存在,則判斷當前行是否以'''開頭,是則將is_comment
設為True,否則進行空行、當前行注釋以及代碼行的判斷,如果is_comment
已經為True即,多行注釋已經開始,則判斷當前行是否以'''結尾,是則將is_comment
設為False,同時增加注釋的行數。表示多行注釋已經結束,反之繼續(xù),此時多行注釋還未結束
# -*- coding:utf-8 -*- #!python3 path = 'test.py' with open(path,'r',encoding='utf-8') as f: code_lines = 0 #代碼行數 comment_lines = 0 #注釋行數 blank_lines = 0 #空白行數 內容為'\n',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)
運行結果:
注釋:4
空行:2
代碼:26
注:這里的Python測試文件test.py如下:
# -*- coding:utf-8 -*- #!python3 #九九乘法表 for i in range(1, 10): for j in range(1, i+1): print("%d*%d=%d\t" % (j, i, i*j), end="") print() #斐波那契數列 0,1,1,2,3,5,8,... num=int(input("需要幾項?")) n1=0 n2=1 count=2 if num<=0: print("請輸入一個整數。") elif num==1: print("斐波那契數列:") print(n1) elif num==2: print("斐波那契數列:") print(n1,",",n2) else: print("斐波那契數列:") print(n1,",",n2,end=" , ") while count<num: sum=n1+n2 print(sum,end=" , ") n1=n2 n2=sum count+=1 print()
感興趣的朋友可以自己測試一下~
PS:這里再為大家推薦2款相關統(tǒng)計工具供大家參考:
在線字數統(tǒng)計工具:
http://tools.jb51.net/code/zishutongji
在線字符統(tǒng)計與編輯工具:
http://tools.jb51.net/code/char_tongji
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
AMP?Tensor?Cores節(jié)省內存PyTorch模型詳解
這篇文章主要為大家介紹了AMP?Tensor?Cores節(jié)省內存PyTorch模型詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10Python lxml解析HTML并用xpath獲取元素的方法
今天小編就為大家分享一篇Python lxml解析HTML并用xpath獲取元素的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01