C# for Sentiment Analysis in Text


Sentiment analysis is the process of determining the sentiment or emotional tone in a piece of text, whether it's positive, negative, or neutral. C# can be used for sentiment analysis by integrating with services like the Azure Cognitive Services Text Analytics API. In this example, we'll demonstrate how to analyze the sentiment of text using C#.


Sample C# Code for Sentiment Analysis


Here's a basic example of C# code for performing sentiment analysis using the Azure Cognitive Services Text Analytics API. Replace `'YOUR_SUBSCRIPTION_KEY'` and `'YOUR_API_ENDPOINT'` with your actual subscription key and API endpoint:


using System;
using System.Net.Http;
using System.Threading.Tasks;
class SentimentAnalyzer
{
private const string subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
private const string endpoint = "YOUR_API_ENDPOINT";
public static async Task<string> AnalyzeSentimentAsync(string text)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
var requestBody = new
{
documents = new[]
{
new { language = "en", id = "1", text = text }
}
};
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(requestBody));
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "application/json");
var response = await client.PostAsync(endpoint, content);
var responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
}
}
class Program
{
static async Task Main()
{
string textToAnalyze = "I love this product! It's amazing!";
string sentimentResult = await SentimentAnalyzer.AnalyzeSentimentAsync(textToAnalyze);
Console.WriteLine("Original Text: " + textToAnalyze);
Console.WriteLine("Sentiment Analysis Result: " + sentimentResult);
}
}

This code demonstrates how to analyze the sentiment of text using the Azure Cognitive Services Text Analytics API. In a real application, you would handle larger volumes of text and potentially perform more sophisticated sentiment analysis.


Sample HTML Text Input Form


Below is a simple HTML form for entering text to be analyzed: