| 2 | |
| 3 | |
| 4 | class Parser: |
| 5 | def __init__(self, path): |
| 6 | self.entity_mentions = [] |
| 7 | self.event_mentions = [] |
| 8 | self.relation_mentions = [] |
| 9 | self.parse_xml(path + '.apf.xml') |
| 10 | |
| 11 | def parse_xml(self, xml_path): |
| 12 | tree = ElementTree.parse(xml_path) |
| 13 | root = tree.getroot() |
| 14 | for child in root[0]: |
| 15 | if child.tag == 'entity': |
| 16 | self.entity_mentions.extend(self.parse_entity_tag(child)) |
| 17 | elif child.tag in ['value', 'timex2']: |
| 18 | self.entity_mentions.extend(self.parse_value_timex_tag(child)) |
| 19 | elif child.tag == 'event': |
| 20 | self.event_mentions.extend(self.parse_event_tag(child)) |
| 21 | elif child.tag == 'relation': |
| 22 | self.relation_mentions.extend(self.parse_relation_tag(child)) |
| 23 | |
| 24 | @staticmethod |
| 25 | def parse_entity_tag(node): |
| 26 | entity_mentions = [] |
| 27 | |
| 28 | for child in node: |
| 29 | if child.tag != 'entity_mention': |
| 30 | continue |
| 31 | extent = child[0] |
| 32 | head = child[1] |
| 33 | charset = extent[0] |
| 34 | head_charset = head[0] |
| 35 | |
| 36 | entity_mention = dict() |
| 37 | entity_mention['entity-id'] = child.attrib['ID'] |
| 38 | entity_mention['entity-type'] = '{}:{}'.format(node.attrib['TYPE'], node.attrib['SUBTYPE']) |
| 39 | entity_mention['text'] = charset.text |
| 40 | entity_mention['position'] = [int(charset.attrib['START']), int(charset.attrib['END'])] |
| 41 | entity_mention["head"] = {"text": head_charset.text, |
| 42 | "position": [int(head_charset.attrib['START']), int(head_charset.attrib['END'])]} |
| 43 | |
| 44 | entity_mentions.append(entity_mention) |
| 45 | |
| 46 | return entity_mentions |
| 47 | |
| 48 | @staticmethod |
| 49 | def parse_relation_tag(node): |
| 50 | relation_mentions = [] |
| 51 | |
| 52 | for child in node: |
| 53 | if child.tag != 'relation_mention': |
| 54 | continue |
| 55 | extent = child[0] |
| 56 | charset = extent[0] |
| 57 | |
| 58 | relation_mention = dict() |
| 59 | relation_mention['relation-id'] = child.attrib['ID'] |
| 60 | relation_mention['relation-type'] = '{}:{}'.format(node.attrib['TYPE'], node.attrib['SUBTYPE']) |
| 61 | relation_mention['text'] = charset.text |