Write a function named lineStats that finds the number of words and the number o
ID: 3864529 • Letter: W
Question
Write a function named lineStats that finds the number of words and the number of characters on each line of a file and writes those statistics to a corresponding line of a new file, separated by a space. (Hint: when you read a line from a file, the endline character is included. Do not include the endline in the number of characters on the line.)
The function lineStats takes two parameters:
1. infile, a string, the name of an input file that exists before lineStats is called
2. outfile, a string, the name of an output file that lineStats creates and writes to.
For example, if the following is the content of the file promisedLand.txt:
The dogs on main street howl,
'cause they understand,
And I believe in a promised land I believe in a promised land...
The following function call:
inF = 'promisedLand.txt'
outF = 'promisedLandStats.txt'
lineStats(inF, outF)
should create the file promisedLandStats.txt with the content:
6 29
3 23
0 0
7 32
6 31
Answer in Python
Explanation / Answer
import sys
inF = 'promisedLand.txt'
outF = 'promisedLandStats.txt'
lineStats(inF, outF)
def lineStats(infile, outfile):
with open(infile, 'r') as inf:
for line in inf:
words = line.split()
num_words += len(words)
num_chars += len(line)-1
out = open(outfile,'a')
out.write(num_words)
out.write(" ")
out.write(num_chars)
out.write(" ")
close(out)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.