final readonly class Result implements JsonSerializable is what Sentiment::analyze() and Analyzer::analyze() return.
use Risan\Sentiment\Sentiment;
$result = Sentiment::analyze('VADER is smart, handsome, and funny.');
$result->label; // Label::Positive
$result->compound; // 0.8316
$result->positive; // 0.746
$result->negative; // 0.0
$result->neutral; // 0.254
The properties are read-only, so you can pass a result around and cache it safely. You normally never create one yourself.
Properties
| Property | Type | Range | Description |
|---|---|---|---|
$label |
Label |
The verdict. It comes from compound and the threshold of the analyzer. |
|
$compound |
float |
-1 to 1 | Overall score, with 4 decimals. Negative means negative sentiment. |
$positive |
float |
0 to 1 | Share of positive signal, with 3 decimals. |
$negative |
float |
0 to 1 | Share of negative signal, with 3 decimals. |
$neutral |
float |
0 to 1 | Share of neutral content, with 3 decimals. |
positive, negative and neutral add up to about 1. Empty text gives 0.0 for the compound and for all three shares. See Understanding the scores.
Methods
isPositive()
Returns true when $label is Label::Positive.
public function isPositive(): bool
isNegative()
Returns true when $label is Label::Negative.
public function isNegative(): bool
isNeutral()
Returns true when $label is Label::Neutral.
public function isNeutral(): bool
For the result above:
$result->isPositive(); // true
$result->isNegative(); // false
$result->isNeutral(); // false
toArray()
Returns the result as a plain array. The label is its string value.
$result->toArray();
// [
// 'label' => 'positive',
// 'compound' => 0.8316,
// 'positive' => 0.746,
// 'negative' => 0.0,
// 'neutral' => 0.254,
// ]
public function toArray(): array
jsonSerialize()
Returns the same array as toArray(). json_encode() calls it, so you can encode a result directly.
echo json_encode($result);
// {"label":"positive","compound":0.8316,"positive":0.746,
// "negative":0,"neutral":0.254}
public function jsonSerialize(): array
PHP drops the trailing .0 of whole floats in JSON, so 0.0 becomes 0. Pass JSON_PRESERVE_ZERO_FRACTION to keep 0.0.