By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,996 Members | 1,498 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,996 IT Pros & Developers. It's quick & easy.

How to read data from a closed file and use that data?

P: 32
I'm trying to make a definition(writeHistogram) to write a histogram and I can't figure it out. I understand the concept of it, but I just can't figure out how to do it. Could someone help me within the hour. It is suppose to take the data from tallies.txt and have a similar output, except it suppose to show the percents as "a - b, c - d, and e - e" instead of a, b, c, d and e.

Thank You!

Expand|Select|Wrap|Line Numbers
  1. class TallySheet:
  2.   """Manage tallies for a collection of values.
  3.  
  4.   Values can either be from a consecutive range of integers, or a
  5.   consecutive sequence of characters from the alphabet.
  6.   """
  7.   def __init__(self, minVal, maxVal):
  8.     """Create an initially empty tally sheet.
  9.  
  10.     minVal    the minimum acceptable value for later insertion
  11.     maxVal    the minimum acceptable value for later insertion
  12.     """
  13.     self._minV = minVal
  14.     self._maxV = maxVal
  15.     maxIndex = self._toIndex(maxVal)
  16.     self._tallies = [0] * (maxIndex + 1)   # a list of counters, each initially zero
  17.  
  18.   def increment(self, val):
  19.     """Increment the tally for the respective value.
  20.  
  21.     raise a TypeError if the given value is not of the proper type
  22.     raise a ValueError if the given value is not within proper range
  23.     """
  24.     ind = self._toIndex(val)
  25.     if not 0 <= ind < len(self._tallies):
  26.       raise ValueError('parameter '+str(val)+' out of range')
  27.     self._tallies[ind] += 1
  28.  
  29.   def getCount(self, val):
  30.     """Return the total number of current tallies for the given value.
  31.  
  32.     raise a TypeError if the given value is not of the proper type
  33.     raise a ValueError if the given value is not within proper range
  34.     """
  35.     ind = self._toIndex(val)
  36.     if not 0 <= ind < len(self._tallies):
  37.       raise ValueError('parameter '+str(val)+' out of range')
  38.     return self._tallies[ind]
  39.  
  40.   def getTotalCount(self):
  41.     """Return the total number of current tallies."""
  42.     return sum(self._tallies)
  43.  
  44.   def _toIndex(self, val):
  45.     """Convert from a native value to a legitimate index.
  46.  
  47.     Return the resulting index (such that _minV is mapped to 0)
  48.     """
  49.     try:
  50.       if isinstance(self._minV, str):
  51.         i = ord(val) - ord(self._minV)
  52.       else:
  53.         i = int( val - self._minV )
  54.     except TypeError:
  55.       raise TypeError('parameter '+str(val)+' of incorrect type')
  56.     return i
  57.  
  58.   def writeTable(self, outfile):
  59.     """Write a comprehensive table of results.
  60.  
  61.     Report each value, the count for that value, and the percentage usage.
  62.  
  63.     outfile   an already open file with write access.
  64.     """
  65.     outfile.write('Value  Count Percent \n----- ------ -------\n')
  66.     total = max(self.getTotalCount(), 1)  # avoid division by zero
  67.     for ind in range(len(self._tallies)):
  68.       label = self._makeLabel(ind)
  69.       count = self._tallies[ind]
  70.       pct = 100.0 * count / total
  71.       outfile.write('%s %6d %6.2f%%\n' % (label, count, pct))
  72.  
  73.   def _makeLabel(self, ind):
  74.     """Convert index to a string in native range."""
  75.     if isinstance(self._minV, int):
  76.       return '%5d' % (ind + self._minV)
  77.     else:
  78.       return '  %s  ' % chr(ind + ord(self._minV))
  79.  
  80.  
  81. if __name__ == '__main__':
  82.   t = TallySheet('a', 'e')
  83.  
  84.   for i in range(10):
  85.     t.increment('a')
  86.  
  87.   if t.getCount('a') == 10:
  88.     print 'Test1: Success'
  89.   else:
  90.     print 'Test1: Failure'
  91.  
  92.   for i in range(5):
  93.     t.increment('b')
  94.  
  95.   if t.getCount('b') == 5:
  96.     print 'Test2: Success'
  97.   else:
  98.     print 'Test2: Failure'
  99.  
  100.   for i in range(10):
  101.     t.increment('c')
  102.  
  103.   if t.getCount('c') == 10:
  104.     print 'Test3: Success'
  105.   else:
  106.     print 'Test3: Failure'
  107.  
  108.   for i in range(5):
  109.     t.increment('d')
  110.  
  111.   if t.getCount('d') == 5:
  112.     print 'Test4: Success'
  113.   else:
  114.     print 'Test4: Failure'
  115.  
  116.   if t.getTotalCount() == 30:
  117.     print 'Test5: Success'
  118.   else:
  119.     print 'Test5: Failure'
  120.  
  121.   f = file('tally.txt', 'w')
  122.   t.writeTable(f)
  123.   f.close()
  124.   print "Please open and check tally.txt file"
  125.   f2 = file('histogram.txt','w')
  126.   t.writeHistogram(f2, f)
  127.   f2.close()
  128.   print "Please open and check histogram.txt file"
  129.  
  130.   raw_input("Press the ENTER key to continue...")
  131.  
  132.  
Any help would be much appreciated! Thank you once again.
Nov 15 '10 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.