Advertisement
Procy0n

Cog409: Sarja 5

Mar 6th, 2011
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.40 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # Sakari Vaelma
  3. """Assignment set 5, assignments 1 and 2 by Sakari Vaelma, 013328180"""
  4.  
  5.  
  6. # A helper class for assignment 2
  7. class Frequency:
  8.     """Calculate frequencies for any immutable object in a sequencei"""
  9.     frequencies = {}
  10.    
  11.     def add(self, item):
  12.         """Add a immutable to frequencies, return None."""
  13.         self.frequencies[item] = self.frequencies.get(item, 0) + 1
  14.  
  15.     def sorted(self):
  16.         """
  17.        Return all (item, frequency) in a list, sorted by frequency.
  18.  
  19.        The resulting frequencies are in descending order.
  20.        """
  21.         return sorted(self.frequencies.items(),
  22.                       key=lambda a: a[1], # Sorting by the 2nd item (frequency)
  23.                       reverse=True)
  24.    
  25.     def __str__(self):
  26.         """Prints a nicely formatted list of frequencies, descending order"""
  27.         return "\n".join(["\t%s: %s" % items
  28.                           for items
  29.                           in self.sorted()])
  30.  
  31.  
  32. # Assignment 1
  33. def read_file(filename):
  34.     """Read data from file and return it in a list of dictionaries."""
  35.     data = []
  36.  
  37.     with open(filename) as datafile:
  38.         for line in datafile:
  39.             line = line.strip()
  40.  
  41.             # Some concepts may not have attributes
  42.             if " " in line:
  43.                 meta, attributes = line.split(" ", 1)
  44.             else:
  45.                 meta, attributes = line, ""
  46.  
  47.             meta, attributes = meta.split("_"), attributes.split()
  48.             data.append({'concept': meta[0][1:], # Leading hash removed
  49.                          'group': meta[1],
  50.                          'participant': int(meta[2]),
  51.                          'education': meta[3],
  52.                          'attributes': attributes})
  53.  
  54.     return data
  55.  
  56. # Assignment 2
  57. def attributes_per_concept(data):
  58.     """Calculate frequencies of attributes per concept"""
  59.     concepts = {}
  60.  
  61.     for line in data:
  62.         concept, attributes = line['concept'], line['attributes']
  63.         if not concepts.has_key(concept):
  64.             concepts[concept] = Frequency()
  65.         map(concepts[concept].add, attributes)
  66.  
  67.     # Printing a table of concepts, attributes and frequencies:
  68.     for concept, frequencies in concepts.items():
  69.         print "Concept: %s\n%s\n" % (concept, frequencies)
  70.  
  71.  
  72. if __name__ == "__main__":
  73.     # Testing
  74.     attributes_per_concept(read_file("attribuutiot.txt"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement