473,385 Members | 1,341 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,385 software developers and data experts.

Reading data from a txt file and making a graph with the given data

32
I'm trying to make a bar graph with the histogram data I get from the histogram.txt file after I run the scripts. How would I go about doing this?

File 1:
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.   def writeHistogram(self, output, source):
  81.       '''Using the information created within writeTable,
  82.       create a histogram that compiles the data from the source file
  83.       into groups of consecutive values.'''
  84.       histo = list()
  85.       text = source.read()         # read the contents of the source file which in this case is tally.txt
  86.       text = text.split('\n')          # split each line in the text
  87.       histo.append(text[0] + '\n')
  88.       histo.append(text[1] + '\n')
  89.       for line in text:                   # if there's a blank line, or a \n at the end of the file, delete it
  90.           if line == '':
  91.             text.remove(line)
  92.  
  93.       numLines = len(text)         # this will help set up how long the loops need to be that are upcoming
  94.  
  95.       if numLines % 2 == 1:      # if the number of lines is odd then the last line needs to be duplicated
  96.           text.append(text[numLines - 1])
  97.       for x in range(2, numLines, 2):       # this loop splits each line into individual pieces then adds the parts together
  98.         j = text[x].split()                          # split the first line
  99.         k = text[x+1].split()                    # split the second line
  100.         label = j[0] + '-' + k[0]               # the label is the first parts added together ie. 'a-b'
  101.         count = int(j[1]) + int(k[1])         # add the counts together
  102.         pct = float(j[2][:-1]) + float(k[2][:-1])       # add the percentages together
  103.         histo.append('%5s %6d %6.2f%%\n' % (label, count, pct))  # create the lines to be written and add them to histo list
  104.  
  105.       for line in histo:
  106.         output.write(line)      # as in writeTable, write a line to the output file
  107.  
  108.  
  109. if __name__ == '__main__':
  110.   t = TallySheet('a', 'e')
  111.  
  112.   for i in range(10):
  113.     t.increment('a')
  114.  
  115.   if t.getCount('a') == 10:
  116.     print 'Test1: Success'
  117.   else:
  118.     print 'Test1: Failure'
  119.  
  120.   for i in range(5):
  121.     t.increment('b')
  122.  
  123.   if t.getCount('b') == 5:
  124.     print 'Test2: Success'
  125.   else:
  126.     print 'Test2: Failure'
  127.  
  128.   for i in range(10):
  129.     t.increment('c')
  130.  
  131.   if t.getCount('c') == 10:
  132.     print 'Test3: Success'
  133.   else:
  134.     print 'Test3: Failure'
  135.  
  136.   for i in range(5):
  137.     t.increment('d')
  138.  
  139.   if t.getCount('d') == 5:
  140.     print 'Test4: Success'
  141.   else:
  142.     print 'Test4: Failure'
  143.  
  144.   if t.getTotalCount() == 30:
  145.     print 'Test5: Success'
  146.   else:
  147.     print 'Test5: Failure'
  148.  
  149.   f = file('tally.txt', 'w')
  150.   t.writeTable(f)
  151.   f.close()
  152.   print "Please open and check tally.txt."
  153.  
  154.   f2 = file('histogram.txt', 'w')
  155.   f = file('tally.txt', 'r')
  156.   t.writeHistogram(f2, f)
  157.   f2.close()
  158.   f.close()
  159.   print "Please open and check histogram.txt."
  160.  
  161.   raw_input("Press the ENTER key to continue...")
  162.  
File 2:
Expand|Select|Wrap|Line Numbers
  1. from TallySheet import *
  2.  
  3. class TallySheetWithHist(TallySheet):
  4.     '''A modified TallySheet Class'''
  5.     def writeHistogram(self, output, source):
  6.       '''Using the information created within writeTable,
  7.       create a histogram that compiles the data from the source file
  8.       into groups of consecutive values.'''
  9.       histo = list()
  10.       text = source.read()         # read the contents of the source file which in this case is tally.txt
  11.       text = text.split('\n')          # split each line in the text
  12.       histo.append(text[0] + '\n')
  13.       histo.append(text[1] + '\n')
  14.       for line in text:                   # if there's a blank line, or a \n at the end of the file, delete it
  15.           if line == '':
  16.             text.remove(line)
  17.  
  18.       numLines = len(text)         # this will help set up how long the loops need to be that are upcoming
  19.  
  20.       if numLines % 2 == 1:      # if the number of lines is odd then the last line needs to be duplicated
  21.           text.append(text[numLines - 1])
  22.       for x in range(2, numLines, 2):       # this loop splits each line into individual pieces then adds the parts together
  23.         j = text[x].split()                          # split the first line
  24.         k = text[x+1].split()                    # split the second line
  25.         label = j[0] + '-' + k[0]               # the label is the first parts added together ie. 'a-b'
  26.         count = int(j[1]) + int(k[1])         # add the counts together
  27.         pct = float(j[2][:-1]) + float(k[2][:-1])       # add the percentages together
  28.         histo.append('%5s %6d %6.2f%%\n' % (label, count, pct))  # create the lines to be written and add them to histo list
  29.  
  30.       for line in histo:
  31.         output.write(line)      # as in writeTable, write a line to the output file
  32.  
  33. if __name__ == '__main__':
  34.   t = TallySheetWithHist('a', 'e')
  35.  
  36.   for i in range(10):
  37.     t.increment('a')
  38.  
  39.   if t.getCount('a') == 10:
  40.     print 'Test1: Success'
  41.   else:
  42.     print 'Test1: Failure'
  43.  
  44.   for i in range(5):
  45.     t.increment('b')
  46.  
  47.   if t.getCount('b') == 5:
  48.     print 'Test2: Success'
  49.   else:
  50.     print 'Test2: Failure'
  51.  
  52.   for i in range(10):
  53.     t.increment('c')
  54.  
  55.   if t.getCount('c') == 10:
  56.     print 'Test3: Success'
  57.   else:
  58.     print 'Test3: Failure'
  59.  
  60.   for i in range(5):
  61.     t.increment('d')
  62.  
  63.   if t.getCount('d') == 5:
  64.     print 'Test4: Success'
  65.   else:
  66.     print 'Test4: Failure'
  67.  
  68.   if t.getTotalCount() == 30:
  69.     print 'Test5: Success'
  70.   else:
  71.     print 'Test5: Failure'
  72.  
  73.   f = file('tally.txt', 'w')
  74.   t.writeTable(f)
  75.   f.close()
  76.   print "Please open and check tally.txt."
  77.  
  78.   f2 = file('histogram.txt', 'w')
  79.   f = file('tally.txt', 'r')
  80.   t.writeHistogram(f2, f)
  81.   f2.close()
  82.   f.close()
  83.   print "Please open and check histogram.txt."
  84.  
  85.   raw_input("Press the ENTER key to continue...")
  86.  
  87.  
Nov 21 '10 #1
2 5276
bvdet
2,851 Expert Mod 2GB
I have never done a bar chart, but I would use matplotlib if I needed to.
Nov 22 '10 #2
dwblas
626 Expert 512MB
Sorry for the late reply, but I stumbled across some links using Tkinter or matplot (which is usually the best way to go).
http://www.scipy.org/Cookbook/Matplotlib/BarCharts
http://www.koders.com/python/fidDE71...aspx?s=tkinter
http://osgeo-org.1803224.n2.nabble.c...td1922503.html
Nov 24 '10 #3

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

Similar topics

1
by: Parzival | last post by:
I have a package that includes some data files. I am planning to use a distutils setup script to install the package. How can I compute a path name for such a data file that will always be relative...
1
by: fabrice | last post by:
Hello, I've got trouble reading a text file (event viewer dump) by using the getline() function... After 200 - 300 lines that are read correctly, it suddenly stops reading the rest of the...
2
by: Domenico Discepola | last post by:
Hello all. Before my arrival at my current employer, our consultants physically set up our MSSQL 7 server as follows: drive c: contains the mssql engine drive d: contains the transaction log...
4
by: Neil10365 | last post by:
I wonder if someone can help me with a small conundrum I am having. This is what I want to achieve: Scenario -------- Each week, I import an excel spreadsheet called Week1.xls into an access...
14
by: Vertilka | last post by:
I need to read binary data file written by C++ program, using my C# application. How do i marshal the bytes i read with my C# code to .NET types. The data is numbers (integers float doubles...
1
by: amfony | last post by:
Hello everyone, first post, very very very noob, and yes its a uni homework thing. My question is how does one read from a given text file strcutured like this: Name, ID, Cost,...
1
by: une | last post by:
hey guys, I have this program to do, but I kind of started forst just te read things from the file and then I would go and make the calculation but it is showing some wierd funnky resualts, I dont...
13
by: anant | last post by:
Hi all The below code is reading string and then tokenizin it and reading all the info. But i want to call a csv file and it should then read a string from dt file. So what midification should i...
4
by: BibI | last post by:
Hi there, I just started programming with PERL and am trying to put together my first little data manipulation program. I am working on a MAC with OSX. I have a data file with the following...
7
by: Man4ish | last post by:
I have one pblm for reading a file randomly for searching the value with in given range. e.g. offset allele id 19 G/T 2066803 20 C/T 2066804 ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.