本文實例講述了Python實現統計python文件中代碼,注釋及空白對應的行數。分享給大家供大家參考,具體如下:
其實代碼和空白行很好統計,難點是注釋行
python中的注釋分為以#開頭的單行注釋
或者以'''開頭以'''結尾 或以"""開頭以"""結尾的文檔注釋,如:
'''hello world'''
和
'''hello world'''
思路是用is_comment
記錄是否存在多行注釋,如果不存在,則判斷當前行是否以'''開頭,是則將is_comment
設為True,否則進行空行、當前行注釋以及代碼行的判斷,如果is_comment
已經為True即,多行注釋已經開始,則判斷當前行是否以'''結尾,是則將is_comment
設為False,同時增加注釋的行數。表示多行注釋已經結束,反之繼續,此時多行注釋還未結束
# -*- coding:utf-8 -*-#!python3path = '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: passprint("注釋:%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=0n2=1count=2if 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+=1print()
感興趣的朋友可以自己測試一下~
PS:這里再為大家推薦2款相關統計工具供大家參考:
在線字數統計工具:
新聞熱點
疑難解答