#!/usr/bin/env python # # wc.py # # Count lines, words, and characters in a file. # # This 'wc.py' file was made executable with # # $ chmod +x wc.py # # which lets it be executed from the command line # without typing 'python', because of the 'unix shebang' # first line of the file. # # If we have a file named 'plain.txt' with this in it # # This is a file full of text. # At least, I *think* that it is. # What do you think? Yes? No? # # then running the # $ ./wc.py plain.txt # file : plain.txt # lines : 3 # words : 20 # letters : 89 # # The filename is taken from the command line with the sys.argv list; # see the source code below for more on how that works. # # Most unix systems have in fact a "wc" program already installed # which does this same calculation : # # $ wc plain.txt # 3 20 89 plain.txt # # Jim Mahoney | Marlboro College | Sep 2014 | MIT License import sys filename = sys.argv[1] # sys.argv is e.g. ['wc', 'file.txt'] file = open(filename, 'r') lines = file.readlines() # = ['first line\n', 'second line\n'] count_lines = len(lines) # len() is the length function. count_words = 0 count_letters = 0 for line in lines: count_letters = count_letters + len(line) count_words = count_words + len(line.split()) # split line at spaces print " file : {} ".format(filename) print " lines : {} ".format(count_lines) print " words : {} ".format(count_words) print " letters : {} ".format(count_letters)