Need Help with this problem, if can provide details in python. Thanks. Implement
ID: 3533351 • Letter: N
Question
Need Help with this problem, if can provide details in python. Thanks.
Implement class TextFile that provides methods to analyze text files -
1) __init__ : that initializes the name of the file (string) and reads the contents of the file into a string
2) print_nchars : prints total number of characters in the file (i.e. number of characters in the string that was read)
3) print_nwords : prints total number of word in the file (i.e. number of words in the string that was read)
**************************** Hints -
about file reading -
fo = open(filename,'r') # opens a file for reading
contents = fo.read( ) # reads all that is inside the file and returns it as a single string
about string processing -
len( contents ) # returns the length of the string named contents
wordList = contents.split( ) # returns all words in the file as a list of strings & len( ) can also be called on a list
Explanation / Answer
class TextFile:
def __init__(self,filename):
self.name= filename;
fo = open(filename,'r')
self.contents = fo.read()
def print_nchars(self):
print(len(self.contents))
def print_nwords(self):
print(len(self.contents.split()))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.