0

i'm completely new to python and I was just curious as to how i'd create a class named 'File' that would allow the following code to execute:

fname = input()
file = File()
if not file.count(fname):
    print("File ", fname, " not present")
else:
    for i in range(10):
        print(str(i) + " = " + "{0:5.2f}".format(file.get_count(i)) + "% ", end = ' ')
2
  • What would File.count and File.get_count do? Are you looking for fnmatch style filename matching? Commented Jul 27, 2018 at 14:27
  • @PatrickHaugh The count function of the File class counts the number of occurrences of each digit and the get count returns the percentage of the occurrence of each digit Commented Jul 27, 2018 at 14:35

1 Answer 1

1

We could create a Counter subclass that accepts a file path, calculates the counts of each character, then provides a method that returns a percentage.

from collections import Counter

class File(Counter):
    def __init__(self, filename, **kwargs):
        with open(filename) as f:  # Caller can deal with FileNotFoundError
            super().__init__(f.read(), **kwargs)
        self.total = sum(self.values())
    def percentage(self, character):  # ranges from 0 to 1
        return self[character]/self.total

file = File("myfile.txt")  # 11223344556789
print(file.percent("1"))
# 0.14285714285714285
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.