using System.Collections.Generic;
public class SentimentAnalyzer
public static string ClassifyText(string text, Dictionary<string, Dictionary<string, int>> trainingData)
if (string.IsNullOrWhiteSpace(text) || trainingData == null || trainingData.Count == 0)
var sentiments = trainingData.Keys.ToList();
var probabilities = new Dictionary<string, double>();
var vocabulary = new HashSet<string>();
foreach (var sentimentData in trainingData.Values)
vocabulary.UnionWith(sentimentData.Keys);
int vocabularySize = vocabulary.Count;
foreach (var sentiment in sentiments)
if (!trainingData.ContainsKey(sentiment)) continue;
var wordsInSentiment = trainingData[sentiment];
double totalWordsInSentiment = wordsInSentiment.Values.Sum();
double logLikelihood = 0.0;
double prior = Math.Log((double)trainingData[sentiment].Count / vocabularySize);
var textWords = text.Split(' ');
foreach (var word in textWords)
if (string.IsNullOrWhiteSpace(word)) continue;
double wordCountInSentiment = wordsInSentiment.ContainsKey(word) ? wordsInSentiment[word] : 0;
double wordProbability = (wordCountInSentiment + 1) / (totalWordsInSentiment + vocabularySize);
logLikelihood += Math.Log(wordProbability);
probabilities[sentiment] = prior + logLikelihood;
string predictedSentiment = "positive";
double maxProbability = double.NegativeInfinity;
foreach (var kvp in probabilities)
if (kvp.Value > maxProbability)
maxProbability = kvp.Value;
predictedSentiment = kvp.Key;
return predictedSentiment;
public static void Main(string[] args)
var trainingData = new Dictionary<string, Dictionary<string, int>>
"positive", new Dictionary<string, int>
"negative", new Dictionary<string, int>
string text1 = "this is a good and great movie";
string sentiment1 = ClassifyText(text1, trainingData);
Console.WriteLine($"'{text1}' is classified as: {sentiment1}");
string text2 = "this is a bad and terrible movie";
string sentiment2 = ClassifyText(text2, trainingData);
Console.WriteLine($"'{text2}' is classified as: {sentiment2}");
string text3 = "this is a good and bad movie";
string sentiment3 = ClassifyText(text3, trainingData);
Console.WriteLine($"'{text3}' is classified as: {sentiment3}");
string text4 = "unknown words test";
string sentiment4 = ClassifyText(text4, trainingData);
Console.WriteLine($"'{text4}' is classified as: {sentiment4}");
var trainingDataOneSentiment = new Dictionary<string, Dictionary<string, int>>
"positive", new Dictionary<string, int>
string text5 = "this is a bad and terrible movie";
string sentiment5 = ClassifyText(text5, trainingDataOneSentiment);
Console.WriteLine($"'{text5}' is classified as: {sentiment5}");