3. Write a Python module, mymod.py, that counts the lines and characters in a fi
ID: 3535578 • Letter: 3
Question
3. Write a Python module, mymod.py, that counts the lines and characters in a file.
It should contain the following functions:
• A countLines(name)function that reads an input file and returns a count
ofthe number of lines in it.
• A countChars(name)function that reads an input file and returns a count
ofthe number of characters in it.
• A countWords(name)function that reads an input file and returns a count
of the number of words in it.
• An avgWordLength(name)function that reads an input file and returns
the average word length about all of the words in the file.
You must also include a test script, test.pythat imports the module and calls each
of these functions and prints their output. Similarly, you must also supply the text
file that you used to test your functions.
Explanation / Answer
def countLine(name):
count = 0
f=open(name)
for line in f:
count=count +1
f.close()
return count
def countChars(name):
count = 0
f=open(name)
for line in f:
for c in line:
count=count +1
f.close()
return count
def countWords(name):
count = 0
f=open(name)
for line in f:
line=line.split()
for i in line:
count=count +1
f.close()
return count
def avgWordLength(name):
return countChars(name)/countWords(name)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.