Actually the code and the blank line is very good statistics, the difficulty is the comment line
Comments in Python are divided into single-line comments that begin with #
Or a document comment that begins with "'" or "" "to End With" ", such as:
‘‘‘
Hello World
"' and
‘‘‘
Hello World "
The idea is to use is_comment to record whether there are multiple lines of comments, if not, then determine whether the current line begins with ' ', is set is_comment to True, otherwise the blank line, the current line comment, and the line of code judgment, if Is_comment is already true, When a multiline comment has already started, it is determined whether the current line ends with a "', or is_comment is set to false, and the number of lines of the comment is increased. Indicates that a multiline comment has ended, and vice versa, when the multiline comment is not over
Path ='test.py'with open (path,'R', encoding='Utf-8') as F:code_lines= 0#number of lines of codeComment_lines = 0#number of comment linesBlank_lines = 0#blank line count ' \ n ', after strip ()Is_comment =False Start_comment_index= 0#record the position of an annotation beginning with "or" " forIndex,lineinchEnumerate (f,start=1): Line= Line.strip ()#remove the opening and closing whitespace characters
#determine if a multiline comment has started if notis_comment:ifLine.startswith ("" "")orLine.startswith ('"""'):is_comment=True Start_comment_index=Index#单行Notes elifLine.startswith ('#'): Comment_lines+ = 1#Blank Line elifline = ="': Blank_lines+ = 1#Line of code Else: Code_lines+ = 1#多行注释已经开始 Else: ifLine.endswith ("" "")orLine.endswith ('"""'):is_comment=False Comment_lines+ = Index-start_comment_index + 1Else: PassPrint("Note:%d"%comment_lines)Print("blank line:%d"%blank_lines)Print("Code:%d"% code_lines)
Statistics the code in the Python file, comments, the number of lines corresponding to the blank