Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This code must be done in python 3. A common utility on word processors is a sma

ID: 3846827 • Letter: T

Question

This code must be done in python 3. A common utility on word processors is a small program called “wc.” This program analyzes a file to determine the number of lines and words contained in the document. Write your own version of wc.

Input: Two file names - one for the input file (infile) and one for the output file (outfile) Output: Print the total number of words and the total number of lines that were contained in the

input file (infile). This output should be printed to the output file (outfile) Your program must meet the following specifications:

1. Get the input and output file names from the user.
2. Use files for all input/output.
3. Compute the number of words/lines in the input file and print the result to the output file. 4. Document the program using Python comments.

Here is a sample run of the program.

If you use the sample file sonnet18.txt provided, the output should look like this:

This output should be printed to the given output file, not the screen.

Explanation / Answer

import sys

fname = raw_input("What file would you like to analyze? ")#take input file name
file should the results be written to? ")#take output file name

num_lines = 0#count lines
num_words = 0#count words

with open(fname, 'r') as f:
for line in f:
words = line.split()#split line using spaces

num_lines += 1
num_words += len(words)

f = open(oname, 'w')
sys.stdout = f#chaneg standard output to file
print "The file "+oname+" had: "
print "words = ",num_words
print "lines = ",num_lines
f.close()

=============================================================

Output:

akshay@akshay-Inspiron-3537:~/Chegg$ python file.py
What file would you like to analyze? input.txt
What file should the results be written to? output.txt

================================================

Output.txt

The file output.txt had:

words = 3
lines = 2

========================================================

input.txt

akshay is
smart

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote