Write a function named fileStats. The function fileStats takes two string parame
ID: 3572738 • Letter: W
Question
Write a function named fileStats. The function fileStats takes two string
parameters: inFile, the name of an input file and outFile, the name of an
output file.
The function fileStats should read and analyze the contents of the input file
and write the statistics it compiles to the output file. The statistics you
should compute about the input file are:
the number of characters;
the number of words;
the number of lines;
the number of digits;
the number of punctuation marks
Each statistic should be written to a separate line of the output file. (Hint:
the string class contains constants named punctuation and digits.)
For example, if the input file contains the following lines:
Lord I'm one, Lord I'm two, Lord I'm three, Lord I'm four,
Lord I'm 500 miles from my home.
500 miles, 500 miles, 500 miles, 500 miles
Lord I'm five hundred miles from my home.
Then an output file with the following lines would be correct:
characters 181
words 35
lines 4
digits 15
punctuation 15
PLEASE ANSWER IN PYTHON
Explanation / Answer
import string
fname = 'kruti.txt'
def fileStats(inFile, outFile):
I = open(inFile)
O = open(outFile, 'w')
F = I.readlines()
s = ''
chars = 0
wordlist = []
for line in F:
chars += len(line)
wordlist += line.split()
s += "characters " + str(chars) + ' '
s += "lines " + str(len(F)) + ' '
s += "words " + str(len(wordlist)) + ' '
dCount = 0
pCount = 0
for i in wordlist:
for j in i:
if j in string.punctuation: pCount +=1
if j in string.digits: dCount += 1
s += "digits " + str(dCount) + ' ' + 'punctuation ' + str(pCount) + ' '
O.write(s)
O.close()
fileStats(fname, 'out.txt')
kruti.txt
Lord I'm one, Lord I'm two, Lord I'm three, Lord I'm four,
Lord I'm 500 miles from my home.
500 miles, 500 miles, 500 miles, 500 miles
Lord I'm five hundred miles from my home.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.