其實代碼和空白行很好統計,難點是注釋行
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 #空白行數 內容為'\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)