3
$\begingroup$

I am looking to create a function that will take a text and parameter strings "neg","pos", and "sum" and calculate a sentiment value for the text. I want to use ReplaceAll and/or "If' for this. I have two lists, one with negative (negativeWords) and one with positive words (positiveWords), and I want the function to assign the value of +1 to words in the text that are also in the positive words list, -1 to words in the text that are also in the negative words list, and 0 for words that are in neither list, and then calculate the sum of those numbers.

This is what I have so far but I am stumped :/

ToLowerCase@TextWords@text_ /. {negativeWords -> -1, positiveWords -> 1, ! negativeWords && ! positiveWords -> 0}

$\endgroup$
1
  • 1
    $\begingroup$ Welcome to Mathematica StackExchange! If I understand correctly, you have your own predefined lists of positive and negative words? Can you please include a short example of these lists and a text in your question? This way, we can more easily make a good answer and test if it works as you expect. $\endgroup$
    – Domen
    Commented Apr 7, 2023 at 20:13

1 Answer 1

2
$\begingroup$

An Association together with Lookup and the default value 0 might do and should be reasonably efficient.

negativeWords = {"A", "B"};
positiveWords = {"a", "b"};

s = "A a b C, B a b A? A B b a c!";

a = Merge[{AssociationThread[positiveWords, 1], AssociationThread[negativeWords, -1]}, First]

Lookup[a, TextWords[s], 0]

{-1, 1, 1, 0, -1, 1, 1, -1, -1, -1, 1, 1, 0}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.