[Tutor] character counter

Sander Sweers sander.sweers at gmail.com
Mon Jun 29 11:44:09 CEST 2009


2009/6/27 julie <youthcares.iiba at gmail.com>:
> file = open("/Users/meitalamitai/Documents/Computer
> Science/Python/Homework/Lorem_Ipsum.py")
> lines = 0
> for line in file:
>     lines=lines+1
> print '%r has %r lines' % ("Lorem_Ipsum.py", lines)
>    if char >= 1000:
>         break

You can do something like below (untested). The below also includes
white space and punctiation. If you want to exclude those use strip().

-----
filename = "/Users/meitalamitai/Documents/Computer
Science/Python/Homework/Lorem_Ipsum.py"
file = open(filename, "r") # Explicitely open the file readonly
lines = file.split() # Split the file into a list so we can use len()
on it and iterate over the lines

linecount = len(lines) # Get the number of lines
totalcharcount = 0 # Set initial total count to zero
count = 1 # Starting count at one

print "The file has %s lines" % linecount

for line in lines:
    charcount = len(line) # Get character count
    print "Line %s has %s character (including punctuation and white
space)." % (count, charcount)
    totalcharcount += charcount #Add the charcount to the total charcount

print "The total file character count is %s" % totallinecount
-----

Hope this helps.

Greets
Sander


More information about the Tutor mailing list