Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- #NoComments.py
- #Python2.7
- #Chris Clarke
- #13.08.2015
- """
- Count number of lines of code, number of commented lines,
- number of blank lines and total lines in a Python module.
- """
- def line_count (fname):
- with open (fname) as file:
- lines = file.readlines ()
- codelines,commentlines,blanklines,total = 0,0,0,0
- comment=False
- for line in lines:
- if len(line) <= 1:
- blanklines += 1
- else:
- i=0
- #locate first non-whitespace character on line
- while line[i]==' ' or line[i]=='\t':
- i += 1
- #check if first non-whitespace is "#"
- if line[i]=='#':
- commentlines += 1
- #check for """ or ''' (start or end of multi-line comment)
- elif line[i:i+3]=="\"\"\"" or line[i:i+3]=="\'\'\'":
- #change comment status
- comment = not comment
- commentlines += 1
- else:
- #check comment status
- if comment:
- #increment commentlines
- commentlines += 1
- else:
- #ye gods! it's actually a line of Python code!!
- codelines += 1
- total += 1
- return codelines,commentlines,blanklines,total
- def main():
- fname = raw_input('Filename for Python module? ')
- codelines,commentlines,blanklines,total = line_count(fname)
- print "Module contains",
- print "%d lines code, %d commented lines, %d blank lines, %d total." % \
- (codelines,commentlines,blanklines,total)
- main()
Advertisement
Add Comment
Please, Sign In to add comment