473,396 Members | 1,990 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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

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
0 1080

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

Similar topics

5
by: Vasilis Serghi | last post by:
Hi all, I am fairly new to C programming and I have come to a stand still. I am trying to create a program that will accept a user input and give the user an output depending on the contents of a...
14
by: Luiz Antonio Gomes Pican?o | last post by:
How i can store a variable length data in file ? I want to do it using pure C, without existing databases. I'm thinking to use pages to store data. Anyone has idea for the file format ? I...
5
by: Pete | last post by:
I having a problem reading all characters from a file. What I'm trying to do is open a file with "for now" a 32bit hex value 0x8FB4902F which I want to && with a mask 0xFF000000 then >> right...
1
by: Napo | last post by:
Hi I use a c# method to open an excel file and to read it's data.But i find a problem that if i changed the excel file data manually by using excelapplication,the readed data by c# method isn't...
4
by: Alessandro | last post by:
Hi everybody, I tried to find some information about my subject with google, but I didn't find anything. I need to read a text file, process the entire content, then kill. In the meantime I...
0
by: Ashish | last post by:
I am using the following code and i am getting the following error :- "Cannot access a closed file." while reading the content of the InputStream. Microsoft suggestes that one should not release...
4
by: greg | last post by:
Hi, I have a read only access file with a linked table that connects to a sybase database. So I can still add data to the table even though its read only since the table is really in sybase. ...
9
by: vineeth | last post by:
Hello all, I have come across a weird problem, I need to determine the amount of bytes read from a file, but couldn't figure it out , My program does this : __ file = open("somefile") data =...
2
by: badwl24 | last post by:
Sir have saved some data in notepad like.... File = F:\Files\SWwork\My Assembly.SLDASM" " Mates" " Coincident1" "" " Coincident1" " Type = 0" " AlignFlag = 1" " ...
0
by: gkhangelani | last post by:
Hi Please assist, I got an error from a server that's running PostgreSQL 7.3.4 on CentOS5 Problem started with the database not starting up showing the following error: LOG: database...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.