File size: 1,235 Bytes
8e12b39
 
 
 
59da9af
 
 
 
 
 
8e12b39
 
 
 
 
 
 
 
 
59da9af
 
 
 
 
8e12b39
59da9af
 
8e12b39
 
 
59da9af
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Literal

AspectWordIndices = tuple[int, ...]
OpinionWordIndices = tuple[int, ...]
Sentiment = Literal["NEG", "NEU", "POS"]
Triplet = tuple[AspectWordIndices, OpinionWordIndices, Sentiment]

word_pattern = re.compile(r"\S+")


@dataclass(frozen=True)
class WordSpan:
    start_index: int
    end_index: int  # this is the letter after the end


@dataclass
class WordSpans:
    spans: list[WordSpan]

    @staticmethod
    def make(text: str) -> WordSpans:
        spans = [
            WordSpan(start_index=match.start(), end_index=match.end())
            for match in word_pattern.finditer(text)
        ]
        return WordSpans(spans)

    def to_indices(self, span: tuple[int, ...]) -> tuple[int, int]:
        word_start = span[0]
        word_start_span = self.spans[word_start]

        word_end = span[-1]
        word_end_span = self.spans[word_end]

        return word_start_span.start_index, word_end_span.end_index - 1


@dataclass(frozen=True)
class CharacterIndices:
    aspect_start_index: int
    aspect_end_index: int
    aspect_term: str
    opinion_start_index: int
    opinion_end_index: int
    opinion_term: str