예제 #1
0
        static string SentimentAnalysisExample(TextAnalyticsClient client, string text)
        {
            string            inputText         = text;
            string            response          = "";
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");
            response = response + $"Document sentiment: {documentSentiment.Sentiment}\n";


            var si = new StringInfo(inputText);

            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"      Text: \"{si.SubstringByTextElements(sentence.GraphemeOffset, sentence.GraphemeLength)}\"");
                response = response + $"      Text: \"{si.SubstringByTextElements(sentence.GraphemeOffset, sentence.GraphemeLength)}\"\n";
                Console.WriteLine($"      Sentence sentiment: {sentence.Sentiment}");
                response = response + $"      Sentence sentiment: {sentence.Sentiment}" + "\n";
                Console.WriteLine($"      Positive score: {sentence.ConfidenceScores.Positive:0.00}");
                response = response + $"      Positive score: {sentence.ConfidenceScores.Positive:0.00} ";
                Console.WriteLine($"      Negative score: {sentence.ConfidenceScores.Negative:0.00}");
                response = response + $"      Negative score: {sentence.ConfidenceScores.Negative:0.00} ";
                Console.WriteLine($"      Neutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
                response = response + $"      Neutral score: {sentence.ConfidenceScores.Neutral:0.00}\n\n";
            }

            return(response);
        }
        public void AnalyzeSentimentBatchConvenience()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);

            var inputs = new List <string>
            {
                "That was the best day of my life!",
                "This food is very bad.",
                "I'm not sure how I feel about this product.",
                "Pike place market is my favorite Seattle attraction.",
            };

            Debug.WriteLine($"Analyzing sentiment for inputs:");
            foreach (string input in inputs)
            {
                Debug.WriteLine($"    {input}");
            }

            #region Snippet:TextAnalyticsSample2AnalyzeSentimentConvenience
            AnalyzeSentimentResultCollection results = client.AnalyzeSentiment(inputs);
            #endregion

            Debug.WriteLine($"Predicted sentiments are:");
            foreach (AnalyzeSentimentResult result in results)
            {
                TextSentiment sentiment = result.DocumentSentiment;
                Debug.WriteLine($"Document sentiment is {sentiment.SentimentClass.ToString()}, with scores: ");
                Debug.WriteLine($"    Positive score: {sentiment.PositiveScore:0.00}.");
                Debug.WriteLine($"    Neutral score: {sentiment.NeutralScore:0.00}.");
                Debug.WriteLine($"    Negative score: {sentiment.NegativeScore:0.00}.");
            }
        }
예제 #3
0
        public static string AnalyzeSentiment(string feedback)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(feedback);

            return(documentSentiment.Sentiment.ToString());
        }
예제 #4
0
        private static void SentimentAnalysis(string blobName, string recognizedText)
        {
            TextAnalyticsClient client = new TextAnalyticsClient(_textAnalyticsEndpoint, _textAnalyticsApiKeyCredential);

            DocumentSentiment documentSentiment = client.AnalyzeSentiment(recognizedText);

            if (documentSentiment != null)
            {
                _logger.LogInformation($"{blobName}: Text sentiment: {documentSentiment.Sentiment}");

                //Extract Key keyPhrases
                Response <IReadOnlyCollection <string> > response = client.ExtractKeyPhrases(recognizedText);
                IEnumerable <string> keyPhrases       = response.Value;
                StringBuilder        keyPhrasesValues = new StringBuilder();
                foreach (string keyPhrase in keyPhrases)
                {
                    keyPhrasesValues.Append(keyPhrase);
                }

                SaveTrancription(blobName, recognizedText, documentSentiment.Sentiment.ToString(), keyPhrasesValues.ToString());
            }
            else
            {
                _logger.LogError($"{blobName}: Unable to process sentiment");
            }
        }
예제 #5
0
        public string AnalyzeSentiment(string inputMessage)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputMessage);

            return(documentSentiment.Sentiment.ToString());
        }
        public void AnalyzeSentiment()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:AnalyzeSentiment
            string document = @"I had the best day of my life. I decided to go sky-diving and it
                                made me appreciate my whole life so much more.
                                I developed a deep-connection with my instructor as well, and I
                                feel as if I've made a life-long friend in her.";

            try
            {
                Response <DocumentSentiment> response     = client.AnalyzeSentiment(document);
                DocumentSentiment            docSentiment = response.Value;

                Console.WriteLine($"Sentiment was {docSentiment.Sentiment}, with confidence scores: ");
                Console.WriteLine($"  Positive confidence score: {docSentiment.ConfidenceScores.Positive}.");
                Console.WriteLine($"  Neutral confidence score: {docSentiment.ConfidenceScores.Neutral}.");
                Console.WriteLine($"  Negative confidence score: {docSentiment.ConfidenceScores.Negative}.");
            }
            catch (RequestFailedException exception)
            {
                Console.WriteLine($"Error Code: {exception.ErrorCode}");
                Console.WriteLine($"Message: {exception.Message}");
            }
            #endregion
        }
        public void AnalyzeSentimentBatch()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            // Instantiate a client that will be used to call the service.
            var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);


            var inputs = new List <string>
            {
                "That was the best day of my life!",
                "This food is very bad.",
                "I'm not sure how I feel about this product.",
                "Pike place market is my favorite Seattle attraction."
            };

            Debug.WriteLine($"Analyzing sentiment for inputs:");
            foreach (var input in inputs)
            {
                Debug.WriteLine($"    {input}");
            }
            var sentiments = client.AnalyzeSentiment(inputs).Value;

            Debug.WriteLine($"Predicted sentiments are:");
            foreach (var sentiment in sentiments)
            {
                Debug.WriteLine($"Document sentiment is {sentiment.SentimentClass.ToString()}, with scores: ");
                Debug.WriteLine($"    Positive score: {sentiment.PositiveScore:0.00}.");
                Debug.WriteLine($"    Neutral score: {sentiment.NeutralScore:0.00}.");
                Debug.WriteLine($"    Negative score: {sentiment.NegativeScore:0.00}.");
            }
        }
예제 #8
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            AzureKeyCredential credentials = new AzureKeyCredential("<reemplazar-con-tu-text-analytics-key>");
            Uri endpoint = new Uri("<reemplazar-con-tu-endpoint-analytics>");

            string text = req.Query["body"];

            var client = new TextAnalyticsClient(endpoint, credentials);

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            text = text ?? data?.body;

            if (!string.IsNullOrEmpty(text))
            {
                DocumentSentiment documentSentiment = client.AnalyzeSentiment(text);
                return(new OkObjectResult(documentSentiment.Sentiment.ToString()));
            }
            else
            {
                return(new OkObjectResult("This HTTP triggered function executed successfully. Pass a text in the query string or in the request body for a personalized response."));
            }
        }
예제 #9
0
        static double[] SentimentAnalysisPercentages(TextAnalyticsClient client, UserEntry userEntry)
        {
            // don't seem to be using this right now, but might be useful (overall sentiment of entry)
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(userEntry.Prompt);

            double positiveAmount = 0.0;
            double negativeAmount = 0.0;
            double neutralAmount  = 0.0;
            int    numSentences   = 0;

            foreach (var sentence in documentSentiment.Sentences)
            {
                numSentences   = numSentences + 1;
                positiveAmount = positiveAmount + sentence.ConfidenceScores.Positive;
                negativeAmount = positiveAmount + sentence.ConfidenceScores.Negative;
                neutralAmount  = positiveAmount + sentence.ConfidenceScores.Neutral;
            }

            double positivePercentage = positiveAmount / numSentences;
            double negativePercentage = negativeAmount / numSentences;
            double neutralPercentage  = neutralAmount / numSentences;

            double[] percentages = { positivePercentage, negativePercentage, neutralPercentage };
            return(percentages);
        }
예제 #10
0
        //Sentiments
        public List <Phrase> SentimentAnalysis(string textInput)
        {
            List <Phrase> phrases = new List <Phrase>();

            if (!String.IsNullOrEmpty(textInput))
            {
                DocumentSentiment documentSentiment = client.AnalyzeSentiment(textInput);
                Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

                foreach (var sentence in documentSentiment.Sentences)
                {
                    Phrase phrase = new Phrase();

                    phrase.Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString();
                    Console.WriteLine($"\tText: \"{sentence.Text}\"");
                    phrase.PhraseText = sentence.Text;
                    Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                    phrase.Sentiment = sentence.Sentiment.ToString();
                    phrase.Lenght    = sentence.Text.Length;
                    Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
                    phrase.PositiveScore = sentence.ConfidenceScores.Positive;
                    Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
                    phrase.NegativeScore = sentence.ConfidenceScores.Negative;
                    Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
                    phrase.NeutralScore = sentence.ConfidenceScores.Neutral;

                    phrase.Language      = LanguageDetection(phrase.PhraseText);
                    phrase.NamedEntities = EntityRecognition(phrase.PhraseText);
                    phrase.KeyPhrases    = KeyPhraseExtraction(phrase.PhraseText);

                    phrases.Add(phrase);
                }
            }
            return(phrases);
        }
예제 #11
0
        public static string AnalyzeSentiment(string feedback)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            // You will implement these methods later in the quickstart.
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(feedback);

            return(documentSentiment.Sentiment.ToString());
        }
예제 #12
0
        static string SentimentDetection(TextAnalyticsClient client, string textToAnalyze)
        {
            string sentimentLabel = "negative";

            DocumentSentiment documentSentiment = client.AnalyzeSentiment(textToAnalyze);

            sentimentLabel = (documentSentiment.Sentiment.ToString());
            return(sentimentLabel);
        }
        static void Main(string[] args)
        {
            const string SUBSCRIPTION_KEY = "PONER_LA_CLAVE_AQUI";
            const string ENDPOINT         = "PONER_EL_ENDPOINT_AQUI";
            const string TEXTO            = "El viaje por Francia del verano pasado fue genial. Conocimos muchos sitios" +
                                            "(el que más nos gustó fue la Provenza) y a mucha gente. Lo único malo fue el tiempo," +
                                            " bastante lluvioso (sobre todo en Normandía). Muchas gracias a nuestro guía, Pierre Martin.";

            TextAnalyticsClient client = new TextAnalyticsClient(new Uri(ENDPOINT), new AzureKeyCredential(SUBSCRIPTION_KEY));

            /////////////////////////
            //Análisis de opinión (Text Analytics-Sentiment)
            /////////////////////////
            Console.WriteLine("---Análisis de opinión---");

            //Invocamos el método de la API para el análisis de la opinión
            DocumentSentiment opinion = client.AnalyzeSentiment(TEXTO, "es");

            //Procesamos el resultado
            Console.WriteLine($"Opinión general del documento: {opinion.Sentiment}\n");

            foreach (SentenceSentiment oracion in opinion.Sentences)
            {
                Console.WriteLine($"\tOración: \"{oracion.Text}\"");
                Console.WriteLine($"\tOpinión de la oración: {oracion.Sentiment}\n");
            }

            /////////////////////////
            //Frases clave (Text Analytics-Key Phrases)
            /////////////////////////
            Console.WriteLine("---Frases clave---");

            //Invocamos el método de la API para extraer frases clave
            KeyPhraseCollection frases = client.ExtractKeyPhrases(TEXTO, "es");

            //Procesamos el resultado
            foreach (string frase in frases)
            {
                Console.WriteLine(frase);
            }

            /////////////////////////
            //Entidades con nombre (Text Analytics-Named Entity Recognition)
            /////////////////////////
            Console.WriteLine("---Entidades con nombre---");

            //Invocamos el método de la API para extraer las entidades
            CategorizedEntityCollection entidades = client.RecognizeEntities(TEXTO, "es");

            //Procesamos el resultado
            foreach (CategorizedEntity entidad in entidades)
            {
                Console.WriteLine($"{entidad.Text} - Categoría:{entidad.Category}, Subcategoría:{entidad.SubCategory}");
            }
        }
예제 #14
0
        /*
         * The below method gets the user inputs and lets us know the nature of the feedback
         */
        private static void CarryOutTestAnalysis(AzureKeyCredential credentials, Uri endpoint)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);

            Console.WriteLine("Please provide your comments");
            var inputText = Console.ReadLine();
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            Console.WriteLine($"Feedback level: {documentSentiment.Sentiment} feedback\n");
            Console.ReadLine();
        }
예제 #15
0
        /// <summary>
        /// Uses the black magic of Azure to calculate the sentiment of the given string.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="languageHint">A hint as to what language the string is in.</param>
        /// <returns>The results of the Sentiment analysis.</returns>
        public DocumentSentiment Sentiment(string input, string languageHint)
        {
            DocumentSentiment result = null;

            // If we don't have the supported language, the analysis won't be accurate. Skip it.
            if (languageHint.SupportedLanguage())
            {
                result = _client.AnalyzeSentiment(input, languageHint).Value;
            }

            return(result);
        }
예제 #16
0
        private static TextSentiment GetSentiment(string usertext, ILogger log)
        {
            AzureKeyCredential credentials = new AzureKeyCredential(Environment.GetEnvironmentVariable("COG_KEY"));
            Uri endpoint = new Uri(Environment.GetEnvironmentVariable("COG_EP"));
            var client   = new TextAnalyticsClient(endpoint, credentials);

            log.LogInformation($" gor sentence to analyze: {usertext}");
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(usertext);
            TextSentiment     ts = documentSentiment.Sentiment;

            log.LogInformation($"CreateRating:Sentiment Score is: {ts}");
            return(ts);
        }
예제 #17
0
        public SentimentScore Process(string sentence)
        {
            var client = new TextAnalyticsClient(_endpoint, _credentials);

            DocumentSentiment documentSentiment = client.AnalyzeSentiment(sentence, "it");

            return(new SentimentScore
            {
                Positive = documentSentiment.ConfidenceScores.Positive,
                Negative = documentSentiment.ConfidenceScores.Negative,
                Neutral = documentSentiment.ConfidenceScores.Neutral
            });
        }
예제 #18
0
        public static string SentimentScore(string Message)
        {
            var               client            = new TextAnalyticsClient(endpoint, credentials);
            string            inputText         = Message;
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            string responseMessage = $"Document sentiment: {documentSentiment.Sentiment}" +
                                     $"\nText: {documentSentiment.ConfidenceScores.Positive}" +
                                     $"\nText: {documentSentiment.ConfidenceScores.Negative}" +
                                     $"\nText: {documentSentiment.ConfidenceScores.Neutral}";


            return(responseMessage);
        }
        internal override void Analyse(TextAnalyticsClient client)
        {
            if (!Documents.Any() || Documents.Any(d => d == null))
            {
                throw new InvalidOperationException("A document to analyse has not been provided");
            }

            if (string.IsNullOrEmpty(Document.Text))
            {
                throw new InvalidOperationException("Text has not been set for the Document");
            }

            Document.SetResults(client.AnalyzeSentiment(Document.Text));
        }
        public async Task Get_Sentiment_Analysis_Results_Using_TypedHttpClient()
        {
            var document1 = new Document {
                Id = "1", Text = "This is a really negative tweet", Language = "en-gb"
            };
            var document2 = new Document {
                Id = "2", Text = "This is a super positive great tweet", Language = "en-gb"
            };
            var document3 = new Document {
                Id = "3", Text = "This is another really super positive amazing tweet", Language = "en-gb"
            };

            var result1 = new DocumentAnalysis {
                Id = "1", Score = 0
            };
            var result2 = new DocumentAnalysis {
                Id = "2", Score = 0.7
            };
            var result3 = new DocumentAnalysis {
                Id = "3", Score = 0.9
            };

            var documents = new List <Document> {
                document1, document2, document3
            };
            var results = new AnalysisResult {
                Documents = new List <DocumentAnalysis> {
                    result1, result2, result3
                }
            };

            var fakeConfiguration = Substitute.For <IConfiguration>();

            var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(results), Encoding.UTF8, "application/json")
            });

            var fakeHttpClient = new HttpClient(fakeHttpMessageHandler);

            var sut = new TextAnalyticsClient(fakeConfiguration, fakeHttpClient);

            var result = await sut.AnalyzeSentiment(documents);

            result.Documents.Count.ShouldBe(3);
            result.Documents.ShouldContain(f => f.Id == result1.Id && f.Score == result1.Score);
        }
        static void SentimentAnalysisExample(TextAnalyticsClient client)
        {
            string            inputText         = "I had the best day of my life. I wish you were there with me.";
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"\tText: \"{sentence.Text}\"");
                Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
            }
        }
예제 #22
0
        static void SentimentAnalysisExample(TextAnalyticsClient client)
        {
            string            inputText         = "Tive o melhor dia da minha vida. Eu queria que você estivesse lá comigo.";
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText, "pt");

            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"\tText: \"{sentence.Text}\"");
                Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
            }
        }
        public SentimentScores ElaborateSentence(string sentence)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);

            DocumentSentiment documentSentiment = client.AnalyzeSentiment(sentence, "it");

            Console.WriteLine($"Sentence sentiment: {documentSentiment.Sentiment}\n");

            var score = new SentimentScores();

            score.SetSentiment((SentimentScores.TextSentiment)documentSentiment.Sentiment);
            score.Positive = documentSentiment.ConfidenceScores.Positive;
            score.Negative = documentSentiment.ConfidenceScores.Negative;
            score.Neutral  = documentSentiment.ConfidenceScores.Neutral;

            return(score);
        }
예제 #24
0
        public Option <DocumentSentiment> DetectSentiment(string text)
        {
            try
            {
                _logger.LogInformation("trying to detect sentiment for: {0}", text);
                var response = _textAnalyticsClient.AnalyzeSentiment(text);

                _logger.LogInformation("sentiment detected: {0}", response.Value.Sentiment);
                return(Option <DocumentSentiment> .Some(response.Value));
            }
            catch (Exception ex)
            {
                _logger.LogError("can't detect sentiment - ", ex);

                return(Option <DocumentSentiment> .None);
            }
        }
예제 #25
0
        static void SentimentAnalysisExample(TextAnalyticsClient client)
        {
            string inputText = "The FitnessGram PACER Test is a multistage aerobic capacity test that progressively gets more difficult as it continues. The test is used to measure a students aerobic capacity as part of the FitnessGram assessment. Students run back and forth as many times as they can, each lap signaled by a beep sound. The test get progressively faster as it continues until the student reaches their max lap score.";

            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"\tText: \"{sentence.Text}\"");
                Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
            }
        }
예제 #26
0
        static void SentimentAnalysisExample(TextAnalyticsClient client, string inputText)
        {
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

            var si = new StringInfo(inputText);

            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"\tSentence [length {sentence.GraphemeLength}]");
                Console.WriteLine($"\tText: \"{si.SubstringByTextElements(sentence.GraphemeOffset, sentence.GraphemeLength)}\"");
                Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
            }
        }
예제 #27
0
        public static DocumentSentiment GetSentiment(string input)
        {
            var client = new TextAnalyticsClient(endpoint, credentials);
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(input);
            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

            var si = new StringInfo(input);
            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"\tSentence [length {sentence.GraphemeLength}]");
                Console.WriteLine($"\tText: \"{si.SubstringByTextElements(sentence.GraphemeOffset, sentence.GraphemeLength)}\"");
                Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
            }
            return documentSentiment;
        }
예제 #28
0
        public void AnalyzeSentiment()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            // Instantiate a client that will be used to call the service.
            var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);

            string input = "That was the best day of my life!";

            Debug.WriteLine($"Analyzing sentiment for input: \"{input}\"");
            var sentiment = client.AnalyzeSentiment(input).Value;

            Debug.WriteLine($"Sentiment was {sentiment.SentimentClass.ToString()}, with scores: ");
            Debug.WriteLine($"    Positive score: {sentiment.PositiveScore:0.00}.");
            Debug.WriteLine($"    Neutral score: {sentiment.NeutralScore:0.00}.");
            Debug.WriteLine($"    Negative score: {sentiment.NeutralScore:0.00}.");
        }
예제 #29
0
        static void SentimentAnalysisExample(TextAnalyticsClient client)
        {
            string            inputText         = "I had the best day of my life. I wish you were there with me.";
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);

            Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");

            var si = new StringInfo(inputText);

            foreach (var sentence in documentSentiment.Sentences)
            {
                Console.WriteLine($"\tSentence [offset {sentence.Offset}, length {sentence.Length}]");
                Console.WriteLine($"\tText: \"{si.SubstringByTextElements(sentence.Offset, sentence.Length)}\"");
                Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
                Console.WriteLine($"\tPositive score: {sentence.SentimentScores.Positive:0.00}");
                Console.WriteLine($"\tNegative score: {sentence.SentimentScores.Negative:0.00}");
                Console.WriteLine($"\tNeutral score: {sentence.SentimentScores.Neutral:0.00}\n");
            }
        }
예제 #30
0
        // build a overall email sentiment, some scoring could be done also
        static void SentimentAnalysis(TextAnalyticsClient client, string textSource)
        {
            DocumentSentiment documentSentiment = client.AnalyzeSentiment(textSource);

            Console.WriteLine($"\n\tDocument sentiment: {documentSentiment.Sentiment}\n");
            _overallSentiment = documentSentiment.Sentiment.ToString();

            foreach (var sentence in documentSentiment.Sentences)
            {
                double   _positive  = sentence.ConfidenceScores.Positive;
                double   _negative  = sentence.ConfidenceScores.Negative;
                double   _neutral   = sentence.ConfidenceScores.Neutral;
                double[] sentiments = new double[] { _positive, _negative, _neutral };
                double   maxValue   = sentiments.Max();
                double   maxIndex   = sentiments.ToList().IndexOf(maxValue);
                Console.Write($"\tResult: \"{maxIndex + " "+ maxValue}\" ");
            }
            Console.WriteLine();
        }