final class Sentiment is the shortest way to score a text.
use Risan\Sentiment\Language;
use Risan\Sentiment\Sentiment;
$result = Sentiment::analyze('This package is awesome!');
$result->label; // Label::Positive
$result->compound; // 0.6588
$result = Sentiment::analyze(
'Filmnya bagus banget!',
Language::Indonesian,
);
// The language code gives the same result.
$result = Sentiment::analyze('Filmnya bagus banget!', 'id');
Sentiment::analyze('Hello', 'xx'); // throws ValueError
The class keeps one default Analyzer per language. It builds the analyzer the first time you ask for it and reuses it. The constructor is private, so you cannot create an instance. For custom words or thresholds, use Analyzer.
Methods
analyze()
Scores a text with the default analyzer of the given language.
public static function analyze(
string $text,
Language|string $language = Language::English,
): Result
Parameters
| Name | Type | Description |
|---|---|---|
$text |
string |
The text to analyze. Any length, including empty. |
$language |
Language|string |
A Language case, or its code: 'en' or 'id'. Defaults to English. |
Returns a Result.
Throws
| Exception | When |
|---|---|
ValueError |
$language is a string that is not a known code. |
Invalid UTF-8 never throws. The package drops the invalid bytes and scores the rest. Empty or whitespace-only text returns all zeros and a neutral label.