File size: 1,361 Bytes
8e12b39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import ast
from pathlib import Path

import pandas as pd


def read_sem_eval_file(file: str | Path) -> pd.DataFrame:
    df = pd.read_xml(file)[["text"]]
    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