def words(line): """ Count the number of words in the string line. """ words = 0 for pos in range(len(line)): # line[pos] is the start of a word if it is a non-space # and it is either the start of string or comes after # a space if line[pos]!=" " and (pos==0 or line[pos-1]==" "): words += 1 return words # get the filename and open it filename = raw_input("Filename: ") file = open(filename, "r") # initialize the counters total_lines = 0 total_chars = 0 total_words = 0 for line in file: # clean any trailing whitespace off the string line = line.rstrip() # do the counting total_lines += 1 total_chars += len(line) total_words += words(line) # summary output print "Total lines:", total_lines print "Total words:", total_words print "Total characters:", total_chars