# Compute the number of words, lines and characters in a file or entered on # the keyboard. The behaviour of the program varies with the number of # command line parameters (beyond the name of the .py file): # # No command line parameters: Input is read from the keyboard (use ctrl-d to # indicate the end of input) and the results are printed on the screen # # One command line parameter: Input is read from a file and the results # are printed on the screen # # Two command line parameters: Input is read from a file and the results are # saved in a file # # Three or more command line parameters: An error message is displayed # import sys # Read from the keyboard and write to the screen if len(sys.argv) == 1: inf = sys.stdin outf = sys.stdout # Read from a file and write to the screen elif len(sys.argv) == 2: inf = open(sys.argv[1], "r") outf = sys.stdout # Read from a file and write to a file elif len(sys.argv) == 3: inf = open(sys.argv[1], "r") outf = open(sys.argv[2], "w") # Too many command line parameters were provided else: print("You must start this program with at nost 2 command line parameters beyond the name of the .py file.") print("") print(sys.argv[0], " ") quit() # Count the words, lines and characters in the input file num_lines = 0 num_chars = 0 num_words = 0 line = inf.readline() while line != "": num_lines = num_lines + 1 num_chars = num_chars + len(line) # Use split to generate a list of words, then compute the length of the # list to get the number of words num_words = num_words + len(line.split()) # Read the next line from the file line = inf.readline() # Save the number of words, lines and characters in the output file outf.write("Lines: " + str(num_lines) + "\n") outf.write("Words: " + str(num_words) + "\n") outf.write("Chars: " + str(num_chars) + "\n") # Close the files inf.close() outf.close()