diff --git a/fluents/annotations.py b/fluents/annotations.py index e2b52b4..56f82c5 100644 --- a/fluents/annotations.py +++ b/fluents/annotations.py @@ -58,3 +58,46 @@ class DictAnnotationHandler(AnnotationHandler): def get_annotation_names(self): return self._dict.keys() + +def read_annotations_file(filename): + """Read annotations from file. + + Reads annotations from a tab delimited file of the format: + dimname annotation_name1 annotation_name2 ... + id1 Foo 0.43 + id2 Bar 0.59 + """ + + ann = DictAnnotationHandler() + dimname = None + annotation_dicts = [] + annotation_names = [] + + fd = open(filename) + + ## Read the first line, which contains the dimension name and + ## annotation names. + line = fd.readline() + values = [x.strip() for x in line.split()] + dimname = values[0] + annotation_names = values[1:] + annotation_dicts = [{} for x in annotation_names] + + ## Read the lines containing the annotations. The first value on + ## each line is an id along the dimension. + while line: + values = [x.strip() for x in line.split()] + for i, x in enumerate(values[1:]): + annotation_dicts[i][values[0]] = x + line = fd.readline() + + fd.close() + + ## Add everything to the annotation object and add the object to + ## the specified dimension. + for i, a in enumerate(annotation_names): + ann.add_annotations(a, annotation_dicts[i]) + + _dim_annotation_handlers[dimname] = ann + return ann + diff --git a/test/system/annotationtest.py b/test/system/annotationtest.py index e40890c..4a1b9de 100644 --- a/test/system/annotationtest.py +++ b/test/system/annotationtest.py @@ -53,5 +53,10 @@ class AnnotationsTest(unittest.TestCase): assert h.get_annotation_names() == ['name'] + def testReadAnnotationsFile(self): + ann = annotations.read_annotations_file('../data/annotations.fann') + assert ann != None + assert ann == annotations.get_dim_handler('dim1') + if __name__ == '__main__': unittest.main()