Skip to content

amounts

Precise English quantities and currencies with bounded object attachment.

AmountMention dataclass

AmountMention(text: str, start: int, end: int, amount: Decimal, object_type: str = '')

An exact quantity and object label at a source-text span.

Attributes:

Name Type Description
text str

Matched quantity text.

start int

Zero-based character offset of the quantity.

end int

Exclusive end offset of the quantity.

amount Decimal

Exact numeric value as a Decimal.

object_type str

Attached object label or normalized currency name.

AmountResult dataclass

AmountResult(text: str, mentions: tuple[AmountMention, ...])

Amount matches for the original input text.

Attributes:

Name Type Description
text str

Analyzed body.

mentions tuple[AmountMention, ...]

Quantities in source order.

to_gkg

to_gkg()

Serialize the amounts field, using an empty string for no matches.

Source code in src/gdelt_regkg/fields/amounts.py
def to_gkg(self):
    """Serialize the amounts field, using an empty string for no matches."""
    return ";".join(m.to_gkg() for m in self.mentions)

analyze_amounts

analyze_amounts(text: str, *, numeric_order: NumericDateOrder | None = None) -> AmountResult

Extract exact English quantities and currencies with short object labels.

Dates, percentages, and indefinite quantities are excluded.

Parameters:

Name Type Description Default
text str

Prepared English body.

required
numeric_order NumericDateOrder | None

mdy or dmy to resolve ambiguous dates before exclusion.

None

Returns:

Type Description
AmountResult

Quantities with exact decimal values and source character offsets.

Raises:

Type Description
TypeError

If text is not a string.

ValueError

If numeric_order is unsupported.

Source code in src/gdelt_regkg/fields/amounts.py
def analyze_amounts(text: str, *, numeric_order: NumericDateOrder | None = None) -> AmountResult:
    """Extract exact English quantities and currencies with short object labels.

    Dates, percentages, and indefinite quantities are excluded.

    Args:
        text: Prepared English body.
        numeric_order: `mdy` or `dmy` to resolve ambiguous dates before exclusion.

    Returns:
        Quantities with exact decimal values and source character offsets.

    Raises:
        TypeError: If `text` is not a string.
        ValueError: If `numeric_order` is unsupported.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    dates = analyze_dates(text, numeric_order=numeric_order)
    excluded = [(m.start, m.end) for m in dates.mentions] + [
        (m.start, m.start + len(m.text)) for m in dates.issues
    ]
    mentions = []
    for match in _RE.finditer(text):
        start, end = match.span()
        if any(start < b and a < end for a, b in excluded) or _PERCENT.match(text[end:]):
            continue
        # Versions, times, identifiers and fractions are not scalar amounts.
        if re.match(r"[.:/][0-9]", text[end:]) or (start and text[start - 1] in ":/"):
            continue
        currency = (match["currency"] or "").strip().casefold()
        obj = _CURRENCY.get(currency, "")
        if not obj:
            cursor = end
            words: list[str] = []
            for _ in range(3):
                following = re.match(r"\s+([A-Za-z]+(?:[-'][A-Za-z]+)*)\b", text[cursor:])
                modifier = bool(
                    following
                    and not words
                    and following[1].casefold() in {"displaced", "injured", "arrested"}
                    and re.match(
                        r"\s+(?:civilians|people|residents|workers|soldiers|children|families)\b",
                        text[cursor + following.end() :],
                        re.I,
                    )
                )
                if not following or (following[1].casefold() in _STOP and not modifier):
                    break
                words.append(following[1])
                cursor += following.end()
            obj = " ".join(words)
        # Bare textual numbers are often pronouns ('one of them').
        if not obj and not currency and not re.search(r"[0-9]", match["number"]):
            continue
        mentions.append(AmountMention(match[0], start, end, _number(match["number"]), obj))
    return AmountResult(text, tuple(mentions))