Statistics the code in the Python file, comments, the number of lines corresponding to the blank

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.