Using Python to count code lines

Source: Internet
Author: User

  

To participate in the glorious road test development class has been more than, Wu always in class also always ask "our class so many times, we practice how many lines of code?" ”。 Here is a face with a crazy look. How do you count it? The number of files is of course not advisable, can be solved by the code of things we resolutely do not do. Recently in the online brush problem also happened to have such a problem, so decided to masturbate.

title: There is a directory in which you have written your own program, to count how many lines of code you have written. Include blank lines and comments, but are listed separately.

First of all, analyze the idea. To smooth the steps of the elephant to install the refrigerator, it is necessary to count the following 7 steps for all lines of code from a given directory:

1. Traverse all files in this directory.

2. Determine if the file ends with ". Py". (Take Python code for example)

3. Open the. py file (do not use w+,w+ to empty the contents of the file)

4. Iterate through each line of the file

5. Determine the contents of each line:

(a) Note: Start with #.

(b) Note: Ends with three quotation marks.

(c) Blank line: No more than white space characters.

(d) Line of code: Other characters are left after whitespace characters.

6. Determine if the end of the file,

7. Close the file and return the result.

After the problem is smoothed out, all that is left is to put the code of each module together like a building block (sample code at the end of this article):

5~9: Import OS, define Code_lines_count function and receive a path form parameter, declare three variables for statistical code lines, comment lines and blank lines

10~13: Traverse the file object obtained by Os.walk, then divide the suffix name of the files with the Splitext function and use the list index [1] to obtain the file suffix name and determine if it ends with ". Py". (You can also use listdir here, but Listdir can only take files from a single-level directory, and you need to determine separately whether the acquired element is a file or a folder, more cumbersome)

Line 12th defines a File_abs_path variable and assigns the absolute path to the file, because the following code is used multiple times, without having to use So.path.join (XX,XX) every time.

14~18: A file ending with ". Py" that was obtained by the previous step is opened with the With method (using with to avoid closing the file), and for open files use a while True loop using ReadLine () to read each row of the file and assign a value to the line variable.

19~39: This code is used to determine whether the line obtained from the previous step ReadLine () is a line of code, a blank line, or a comment line.

19~21: If line is empty, it means taking to the end of the file, at which point the break while loop continues with the next file operation in files.

22~24: Use Strip () to ReadLine () to take the line to go blank processing, if processed by "#" to begin with, it means that this line is a comment line at this time to add 1 operations to the Comm_lines.

25~33: Use Strip () to ReadLine () to take the line to go blank processing, if processed by three single quotation marks or three double quotation marks the beginning of a multi-line comment here, and then determine the number of three quotation marks of the line if 1 means that the comment is divided into multiple lines, Otherwise the comment is one line (one pair of three quotation marks on the same line), the next line is read for the comment for multiple lines, and the comm_lines is not read by a row, and the comment ends if there is three quotation marks on a line, and a break is determined. When the layer while loop (only the notes of the comparison specification are considered here)

34~36: If the read line has been strip () followed by a non-empty and not a comment, it is a line of code and adds 1 to the code_lines.

37~39: If none of the above conditions are satisfied, then a blank line is judged, and the space_lines is added to the 1 operation.

41: Returns the line of code to the line, comment lines, and blank lines.

43: Test code is an instance of running

1 #_*_coding:utf-8_*_2 3 #Count lines of code, blank lines, comments.4 5 ImportOS6 defcode_lines_count (path):7Code_lines =08Comm_lines =09Space_lines =0Ten      forRoot,dirs,filesinchOs.walk (path): One          forIteminchFiles: AFile_abs_path =Os.path.join (Root,item) -Postfix = Os.path.splitext (File_abs_path) [1] -             ifPostfix = ='. PY': the                 #print ' Start: ', File_abs_path - With Open (File_abs_path) as FP: -                      whileTrue: -line =Fp.readline () +                         if  notLine : -                             #print ' Break here,%r '%line +                              Break A                         elifLine.strip (). StartsWith ('#'): at                             #print ' 1, here ', line -Comm_lines + = 1 -                         elifLine.strip (). StartsWith ("" "")orLine.strip (). StartsWith ('"""'): -Comm_lines + = 1 -                             ifLine.count ('"""') ==1orLine.count ("" "") ==1: -                                  whileTrue: inline =Fp.readline () -                                     #print ' 4, here ', line toComm_lines + = 1 +                                     if("" "" inchLineor('"""' inchLine ): -                                          Break the                         elifLine.strip (): *                             #print ' 5, here ', line $Code_lines + = 1Panax Notoginseng                         Else: -                             #print ' 6, here ', line theSpace_lines +=1 +                 #print ' Done ', File_abs_path A     returnCode_lines,comm_lines,space_lines the #Test + Print "Code lines:%d\ncomments lines:%d\nwhitespace lines:%d"%code_lines_count (R'D:\exercises')

--Code of the nature and play games, are playing strange upgrade wear equipment.

Using Python to count code lines

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.