Question: Using Python Its multiple questions but linked to the first problem 8.25 Develop a class Textfile that provides methods to analyze a text file. The
Using Python
Its multiple questions but linked to the first problem
8.25 Develop a class Textfile that provides methods to analyze a text file. The class Textfile will support a constructor that takes as input a file name (as a string) and instantiates a Textfile object associated with the corresponding text file. The Textfile class should support methods nchars(), nwords(), and nlines() that return the number of characters, words, and lines, respectively, in the associated text file. The class should also support methods read() and readlines() that return the content of the text file as a string or as a list of lines, respectively, just as we would expect for file objects. Finally, the class should support method grep() that takes a target string as input and searches for lines in the text file that contain the target string. The method returns the lines in the file containing the target string; in addition, the method should print the line number, where line numbering starts with 0. >>> t = Textfile('raven.txt') File: raven.txt >>> t.nchars() 6299 >>> t.nwords() 1125 >>> t.nlines() 126 >>> print(t.read()) Once upon a midnight dreary, while I pondered weak and weary, ... Shall be lifted - nevermore! >>> t.grep('nevermore') 75: Of `Never-nevermore.` 89: She shall press, ah, nevermore! 124: Shall be lifted - nevermore!
class Textfile():
def __init__(self, filename):
self.file = open(filename)
def nchars(self):
return len(self.file.read())
def nwords(self):
content = self.file.read()
words = content.split()
return len(words)
def nlines(self):
content = self.file.read()
return content.count(' ') 8.26 Add method words() to class Textfile from Problem 8.25. It takes no input and returns a list, without duplicates, of words in the file.
8.27 Add method occurrences() to class Textfile from Problem 8.25. It takes no input and returns a dictionary mapping each word in the file (the key) to the number of times it occurs in the file (the value).
8.28 Add method average() to class Textfile from Problem 8.25. It takes no input and returns, in a tuple object, (1) the average number of words per sentence in the file, (2) the number of words in the sentence with the most words, and (3) the number of words in the sentence with the fewest words. You may assume that the symbols delimiting a sentence are in'!?.'.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
