Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # Sakari Vaelma
- """Assignment set 5, assignments 1 and 2 by Sakari Vaelma, 013328180"""
- # A helper class for assignment 2
- class Frequency:
- """Calculate frequencies for any immutable object in a sequencei"""
- frequencies = {}
- def add(self, item):
- """Add a immutable to frequencies, return None."""
- self.frequencies[item] = self.frequencies.get(item, 0) + 1
- def sorted(self):
- """
- Return all (item, frequency) in a list, sorted by frequency.
- The resulting frequencies are in descending order.
- """
- return sorted(self.frequencies.items(),
- key=lambda a: a[1], # Sorting by the 2nd item (frequency)
- reverse=True)
- def __str__(self):
- """Prints a nicely formatted list of frequencies, descending order"""
- return "\n".join(["\t%s: %s" % items
- for items
- in self.sorted()])
- # Assignment 1
- def read_file(filename):
- """Read data from file and return it in a list of dictionaries."""
- data = []
- with open(filename) as datafile:
- for line in datafile:
- line = line.strip()
- # Some concepts may not have attributes
- if " " in line:
- meta, attributes = line.split(" ", 1)
- else:
- meta, attributes = line, ""
- meta, attributes = meta.split("_"), attributes.split()
- data.append({'concept': meta[0][1:], # Leading hash removed
- 'group': meta[1],
- 'participant': int(meta[2]),
- 'education': meta[3],
- 'attributes': attributes})
- return data
- # Assignment 2
- def attributes_per_concept(data):
- """Calculate frequencies of attributes per concept"""
- concepts = {}
- for line in data:
- concept, attributes = line['concept'], line['attributes']
- if not concepts.has_key(concept):
- concepts[concept] = Frequency()
- map(concepts[concept].add, attributes)
- # Printing a table of concepts, attributes and frequencies:
- for concept, frequencies in concepts.items():
- print "Concept: %s\n%s\n" % (concept, frequencies)
- if __name__ == "__main__":
- # Testing
- attributes_per_concept(read_file("attribuutiot.txt"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement