Skip to content

tone

Dictionary-frequency scoring for the GKG tone field.

ToneLexicon dataclass

ToneLexicon(name: str, positive: frozenset[str], negative: frozenset[str], activity: frozenset[str], self_group: frozenset[str])

Named positive, negative, activity, and self-group token collections.

Categories are normalized and frozen at construction. Empty categories and overlap between categories are supported.

from_json classmethod

from_json(path: str | Path) -> 'ToneLexicon'

Load once outside row loops; JSON needs name and all four categories.

Source code in src/gdelt_regkg/fields/tone.py
@classmethod
def from_json(cls, path: str | Path) -> "ToneLexicon":
    """Load once outside row loops; JSON needs name and all four categories."""
    return _parse_lexicon(Path(path).read_text(encoding="utf-8"))

ToneResult dataclass

ToneResult(tone: float, positive_score: float, negative_score: float, polarity: float, activity_reference_density: float, self_group_reference_density: float, word_count: int, lexicon_name: str)

Tone scores, token count, and the lexicon identity.

Attributes:

Name Type Description
tone float

Positive score minus negative score.

positive_score float

Percentage of tokens matching positive words.

negative_score float

Percentage of tokens matching negative words.

polarity float

Percentage matching either positive or negative words.

activity_reference_density float

Percentage matching activity words.

self_group_reference_density float

Percentage matching self-group words.

word_count int

Total tokens, including repetitions.

lexicon_name str

Name of the dictionary used.

to_gkg

to_gkg() -> str

Serialize six scores and the word count in GKG tone field order.

Source code in src/gdelt_regkg/fields/tone.py
def to_gkg(self) -> str:
    """Serialize six scores and the word count in GKG tone field order."""
    scores = (
        self.tone,
        self.positive_score,
        self.negative_score,
        self.polarity,
        self.activity_reference_density,
        self.self_group_reference_density,
    )
    return ",".join(format(value, ".15g") for value in scores) + f",{self.word_count}"

tokenize_tone

tokenize_tone(text: str) -> list[str]

Return casefolded word/number tokens, retaining internal apostrophes/hyphens.

This explicit local policy is not a verified GDELT tokenizer. Punctuation alone is not a token; stopwords and repeated words stay in the denominator. Input must already be article text, not HTML.

Source code in src/gdelt_regkg/fields/tone.py
def tokenize_tone(text: str) -> list[str]:
    """Return casefolded word/number tokens, retaining internal apostrophes/hyphens.

    This explicit local policy is not a verified GDELT tokenizer. Punctuation
    alone is not a token; stopwords and repeated words stay in the denominator.
    Input must already be article text, not HTML.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str; normalize missing values before scoring")
    return _WORD.findall(_normalize(text))

benchmark_tone_lexicon

benchmark_tone_lexicon(resources_dir: StrPath | None = None) -> ToneLexicon

Compatibility alias for the benchmark-refined default dictionary.

Source code in src/gdelt_regkg/fields/tone.py
def benchmark_tone_lexicon(resources_dir: StrPath | None = None) -> ToneLexicon:
    """Compatibility alias for the benchmark-refined default dictionary."""
    return default_tone_lexicon(resources_dir)

baseline_tone_lexicon

baseline_tone_lexicon(resources_dir: StrPath | None = None) -> ToneLexicon

Version 1, retained for reproducible dictionary builds and comparisons.

Source code in src/gdelt_regkg/fields/tone.py
def baseline_tone_lexicon(resources_dir: StrPath | None = None) -> ToneLexicon:
    """Version 1, retained for reproducible dictionary builds and comparisons."""
    return _cached_tone_lexicon(
        resource_path("lexicons", "tone.v1.json", resources_dir=resources_dir)
    )

analyze_tone

analyze_tone(text: str, *, lexicon: ToneLexicon | None = None) -> ToneResult

Compute dictionary-based tone scores for article text.

Parameters:

Name Type Description Default
text str

Plain article text in the lexicon's language. The default lexicon expects English text or an English translation.

required
lexicon ToneLexicon | None

Reusable tone dictionary. If omitted, load the configured default English dictionary from local resources.

None

Returns:

Type Description
ToneResult

The seven tone components and the name of the dictionary used.

Raises:

Type Description
TypeError

If text is not a string or lexicon is not a ToneLexicon.

ResourceUnavailableError

If the default local dictionary is unavailable.

Examples:

>>> lexicon = ToneLexicon("example", {"good"}, {"bad"}, set(), set())
>>> result = analyze_tone("good good bad", lexicon=lexicon)
>>> result.word_count
3
>>> round(result.tone, 2)
33.33
Source code in src/gdelt_regkg/fields/tone.py
def analyze_tone(text: str, *, lexicon: ToneLexicon | None = None) -> ToneResult:
    """Compute dictionary-based tone scores for article text.

    Args:
        text: Plain article text in the lexicon's language. The default lexicon
            expects English text or an English translation.
        lexicon: Reusable tone dictionary. If omitted, load the configured
            default English dictionary from local resources.

    Returns:
        The seven tone components and the name of the dictionary used.

    Raises:
        TypeError: If text is not a string or lexicon is not a ToneLexicon.
        ResourceUnavailableError: If the default local dictionary is unavailable.

    Examples:
        >>> lexicon = ToneLexicon("example", {"good"}, {"bad"}, set(), set())
        >>> result = analyze_tone("good good bad", lexicon=lexicon)
        >>> result.word_count
        3
        >>> round(result.tone, 2)
        33.33
    """
    tokens = tokenize_tone(text)
    if lexicon is None:
        lexicon = default_tone_lexicon()
    if not isinstance(lexicon, ToneLexicon):
        raise TypeError("lexicon must be a ToneLexicon")
    counts = Counter(tokens)
    total = len(tokens)

    def density(category: frozenset[str]) -> float:
        matches = sum(count for token, count in counts.items() if token in category)
        return 100.0 * matches / total if total else 0.0

    positive = density(lexicon.positive)
    negative = density(lexicon.negative)
    return ToneResult(
        tone=positive - negative,
        positive_score=positive,
        negative_score=negative,
        polarity=density(lexicon._tonal),
        activity_reference_density=density(lexicon.activity),
        self_group_reference_density=density(lexicon.self_group),
        word_count=total,
        lexicon_name=lexicon.name,
    )