Skip to content

Commit 419cbe9

Browse files
committed
Sentiment computation now returns undefined if there is no sentiment data
1 parent 7421d04 commit 419cbe9

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

pipeline/process/nlp/Emojis.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ export class Emojis {
1818
return this.data[emoji] ? this.data[emoji].n : emoji;
1919
}
2020

21-
/** Returns the sentiment of an emoji. e.g. 😡 → negative, ❤ → positive, 🟪 → 0. Always [-1, 1] */
22-
public getSentiment(emoji: string): number {
23-
return this.data[emoji]?.s || 0;
21+
/** Returns the sentiment of an emoji. e.g. 😡 → negative, ❤ → positive, 🟪 → undefined. Always [-1, 1] */
22+
public getSentiment(emoji: string): number | undefined {
23+
return this.data[emoji]?.s;
2424
}
2525

2626
static async load(env: Env) {

pipeline/process/nlp/Sentiment.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export class Sentiment {
6666
let score = 0;
6767
let nearNegator = false;
6868
let nearNegatorDist = 0;
69+
let tokenHits = 0;
6970

7071
for (let i = 0, len = tokens.length; i < len; i++) {
7172
const token = tokens[i];
@@ -76,7 +77,11 @@ export class Sentiment {
7677
nearNegatorDist++;
7778

7879
if (token.tag === "emoji") {
79-
score += this.emojiData.getSentiment(token.text);
80+
const emojiValue = this.emojiData.getSentiment(token.text);
81+
if (emojiValue !== undefined) {
82+
tokenHits++;
83+
score += emojiValue;
84+
}
8085
continue;
8186
}
8287

@@ -93,12 +98,14 @@ export class Sentiment {
9398

9499
const afinnMatch = langDb.afinn.match(slice);
95100
if (afinnMatch) {
101+
tokenHits++;
96102
score += afinnMatch.value * (nearNegator ? -1 : 1);
97103
}
98104
}
99105
}
100106

101-
return score;
107+
// only return score if we found at least one token with sentiment
108+
return tokenHits > 0 ? score : undefined;
102109
}
103110

104111
static async load(env: Env, emojis: Emojis) {

tests/process/nlp/Emojis.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,6 @@ describe("Emojis", () => {
1717
it("should return correct sentiment for common emojis", async () => {
1818
expect(emojis.getSentiment("😡")).toBeNegative();
1919
expect(emojis.getSentiment("❤")).toBePositive();
20-
expect(emojis.getSentiment("🟪")).toBe(0); // rare emoji
20+
expect(emojis.getSentiment("🟪")).toBe(undefined); // rare emoji
2121
});
2222
});

0 commit comments

Comments
 (0)