brilliant_moves

NoComments.py

Aug 13th, 2015
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #!/usr/bin/python
  2. #NoComments.py
  3. #Python2.7
  4. #Chris Clarke
  5. #13.08.2015
  6.  
  7. """
  8. Count number of lines of code, number of commented lines,
  9. number of blank lines and total lines in a Python module.
  10. """
  11.  
  12. def line_count (fname):
  13.     with open (fname) as file:
  14.         lines = file.readlines ()
  15.     codelines,commentlines,blanklines,total = 0,0,0,0
  16.     comment=False
  17.     for line in lines:
  18.         if len(line) <= 1:
  19.             blanklines += 1
  20.         else:
  21.             i=0
  22.             #locate first non-whitespace character on line
  23.             while line[i]==' ' or line[i]=='\t':
  24.                 i += 1
  25.             #check if first non-whitespace is "#"
  26.             if line[i]=='#':
  27.                 commentlines += 1
  28.             #check for """ or ''' (start or end of multi-line comment)
  29.             elif line[i:i+3]=="\"\"\"" or line[i:i+3]=="\'\'\'":
  30.                 #change comment status
  31.                 comment = not comment
  32.                 commentlines += 1
  33.             else:
  34.                 #check comment status
  35.                 if comment:
  36.                     #increment commentlines
  37.                     commentlines += 1
  38.                 else:
  39.                     #ye gods! it's actually a line of Python code!!
  40.                     codelines += 1
  41.         total += 1
  42.     return codelines,commentlines,blanklines,total
  43.  
  44. def main():
  45.     fname = raw_input('Filename for Python module? ')
  46.     codelines,commentlines,blanklines,total = line_count(fname)
  47.     print "Module contains",
  48.     print "%d lines code, %d commented lines, %d blank lines, %d total." % \
  49.     (codelines,commentlines,blanklines,total)
  50.  
  51. main()
Advertisement
Add Comment
Please, Sign In to add comment