import ast from pathlib import Path import pandas as pd from lxml import etree def read_sem_eval_file(file: str | Path) -> pd.DataFrame: root = etree.parse(file) documents = root.xpath("//text/text()") assert isinstance(documents, list), f"cannot parse text from {file}" df = pd.DataFrame({"text": documents}) return df def read_aste_file(file: str | Path) -> pd.DataFrame: df = pd.read_csv( file, sep="####", header=None, names=["text", "triples"], engine="python", ) # There are duplicate rows, some of which have the same triples and some don't # This deals with that by # * first dropping the pure duplicates, # * then parsing the triples and exploding them to one per row # * then dropping the exploded duplicates (have to convert triples back to string for this) # * then grouping the triples up again # * finally sorting the distinct triples df = df.drop_duplicates() df["triples"] = df.triples.apply(ast.literal_eval) df = df.explode("triples") df["triples"] = df.triples.apply(_triple_to_hashable) df = df.drop_duplicates() df = df.groupby("text").agg(list) df = df.reset_index(drop=False) df["triples"] = df.triples.apply(set).apply(sorted) return df def _triple_to_hashable( triple: tuple[list[int], list[int], str] ) -> tuple[tuple[int, ...], tuple[int, ...], str]: aspect_span, opinion_span, sentiment = triple return tuple(aspect_span), tuple(opinion_span), sentiment