# # Compute the number of words, lines and characters in a file. # import sys # Retrieve the name of the file from the command line if len(sys.argv) > 3: print("Usage: python", sys.argv[0], " ") quit() elif len(sys.argv) == 3: # Input from file and output is to a file inf = open(sys.argv[1], "r") outf = open(sys.argv[2], "w") elif len(sys.argv) == 2: # Input from file and output is to the screen inf = open(sys.argv[1], "r") outf = sys.stdout elif len(sys.argv) == 1: # Input from keyboard and output is to the screen inf = sys.stdin outf = sys.stdout # Initialize our counters lines = 0 words = 0 chars = 0 # Read and process every line in the file line = inf.readline() while line != "": # Add one to the line counter lines = lines + 1 # Count the number of words and add that value to the word counter words = words + len(line.split()) # Count the number of characters and add that value to the character counter chars = chars + len(line) # Read the next line from the file line = inf.readline() # Close the file inf.close() # Write the counts to a file outf.write("Lines: " + str(lines) + "\n") outf.write("Words: " + str(words) + "\n") outf.write("Chars: " + str(chars) + "\n") outf.close()