コード例 #1
0
        static AnalyzeSentimentResultCollection SentimentAnalysisWithOpinionMining(TextAnalyticsClient client, List <string> documents)
        {
            AnalyzeSentimentResultCollection reviews = client.AnalyzeSentimentBatch(documents, options: new AnalyzeSentimentOptions()
            {
                IncludeOpinionMining = true
            });

            return(reviews);
        }
        public void AnalyzeSentimentWithOpinionMining()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            #region Snippet:TAAnalyzeSentimentWithOpinionMining
            string reviewA = @"The food and service were unacceptable, but the concierge were nice.
                             After talking to them about the quality of the food and the process
                             to get room service they refunded the money we spent at the restaurant
                             and gave us a voucher for nearby restaurants.";

            string reviewB = @"The rooms were beautiful. The AC was good and quiet, which was key for
                            us as outside it was 100F and our baby was getting uncomfortable because of the heat.
                            The breakfast was good too with good options and good servicing times.
                            The thing we didn't like was that the toilet in our bathroom was smelly.
                            It could have been that the toilet was not cleaned before we arrived.
                            Either way it was very uncomfortable.
                            Once we notified the staff, they came and cleaned it and left candles.";

            string reviewC = @"Nice rooms! I had a great unobstructed view of the Microsoft campus
                            but bathrooms were old and the toilet was dirty when we arrived. 
                            It was close to bus stops and groceries stores. If you want to be close to
                            campus I will recommend it, otherwise, might be better to stay in a cleaner one.";

            var documents = new List <string>
            {
                reviewA,
                reviewB,
                reviewC
            };

            var options = new AnalyzeSentimentOptions()
            {
                IncludeOpinionMining = true
            };
            Response <AnalyzeSentimentResultCollection> response = client.AnalyzeSentimentBatch(documents, options: options);
            AnalyzeSentimentResultCollection            reviews  = response.Value;

            Dictionary <string, int> complaints = GetComplaints(reviews);

            var negativeAspect = complaints.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
            Console.WriteLine($"Alert! major complaint is *{negativeAspect}*");
            Console.WriteLine();
            Console.WriteLine("---All complaints:");
            foreach (KeyValuePair <string, int> complaint in complaints)
            {
                Console.WriteLine($"   {complaint.Key}, {complaint.Value}");
            }
            #endregion
        }
コード例 #3
0
        internal override void Analyse(TextAnalyticsClient client)
        {
            if (!Documents.Any())
            {
                throw new InvalidOperationException("No documents have been added to the Batch Operation");
            }

            foreach (AnalyzeSentimentResult sentimentInDocument in client.AnalyzeSentimentBatch(Documents.Select(d => d.Text)).Value)
            {
                int index = int.Parse(sentimentInDocument.Id);

                if (sentimentInDocument.HasError)
                {
                    Documents[index].SetErrorMessage(sentimentInDocument.Error.Message);
                }
                else
                {
                    Documents[index].SetResults(sentimentInDocument.DocumentSentiment);
                }
            }
        }
コード例 #4
0
        public static Dictionary<string, DocumentSentiment> GetSentiment(Dictionary<string, TextDocumentInput[]> documents)
        {
            Dictionary<string, DocumentSentiment> results = new Dictionary<string, DocumentSentiment>();
            List<TextDocumentInput> inputs = new List<TextDocumentInput>();
            documents.Values.ToList().ForEach(v => inputs.AddRange(v));

            if (inputs.Count > 0) { 
                var client = new TextAnalyticsClient(endpoint, credentials);
                var response = client.AnalyzeSentimentBatch(inputs);
                var batchResults = response.Value;

                documents.Keys.ToList().ForEach(entryId =>
                {
                    var entryResults = batchResults.Where(br =>
                    {
                        var idParts = br.Id.Split(" ");
                        return (idParts[0] == entryId);
                    }).ToList();
                    results.Add(entryId, CombineSentiments(documents[entryId], entryResults));
                });
            }
            return results;
        }
        public void AnalyzeSentimentWithOpinionMining()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            #region Snippet:TAAnalyzeSentimentWithOpinionMining
            var documents = new List <string>
            {
                "The food and service were unacceptable, but the concierge were nice.",
                "The rooms were beautiful. The AC was good and quiet.",
                "The breakfast was good, but the toilet was smelly.",
                "Loved this hotel - good breakfast - nice shuttle service - clean rooms.",
                "I had a great unobstructed view of the Microsoft campus.",
                "Nice rooms but bathrooms were old and the toilet was dirty when we arrived.",
                "We changed rooms as the toilet smelled."
            };

            AnalyzeSentimentResultCollection reviews = client.AnalyzeSentimentBatch(documents, options: new AnalyzeSentimentOptions()
            {
                AdditionalSentimentAnalyses = AdditionalSentimentAnalyses.OpinionMining
            });

            Dictionary <string, int> complaints = GetComplaints(reviews);

            var negativeAspect = complaints.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
            Console.WriteLine($"Alert! major complaint is *{negativeAspect}*");
            Console.WriteLine();
            Console.WriteLine("---All complaints:");
            foreach (KeyValuePair <string, int> complaint in complaints)
            {
                Console.WriteLine($"   {complaint.Key}, {complaint.Value}");
            }
            #endregion
        }
        public void AnalyzeSentimentBatchConvenience()
        {
            string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string apiKey   = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_API_KEY");

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

            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.AnalyzeSentimentBatch(inputs);
            #endregion

            Debug.WriteLine($"Predicted sentiments are:");
            foreach (AnalyzeSentimentResult result in results)
            {
                DocumentSentiment docSentiment = result.DocumentSentiment;
                Debug.WriteLine($"Document sentiment is {docSentiment.Sentiment}, with confidence scores: ");
                Debug.WriteLine($"    Positive confidence score: {docSentiment.ConfidenceScores.Positive}.");
                Debug.WriteLine($"    Neutral confidence score: {docSentiment.ConfidenceScores.Neutral}.");
                Debug.WriteLine($"    Negative confidence score: {docSentiment.ConfidenceScores.Negative}.");
            }
        }
コード例 #7
0
        public void AnalyzeSentimentBatch()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            #region Snippet:TextAnalyticsSample2AnalyzeSentimentBatch
            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "That was the best day of my life!")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "This food is very bad. Everyone who ate with us got sick.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "I'm not sure how I feel about this product.")
                {
                    Language = "en",
                },
                new TextDocumentInput("4", "Pike Place Market is my favorite Seattle attraction.  We had so much fun there.")
                {
                    Language = "en",
                }
            };

            AnalyzeSentimentResultCollection results = client.AnalyzeSentimentBatch(documents, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

            int i = 0;
            Debug.WriteLine($"Results of Azure Text Analytics \"Sentiment Analysis\" Model, version: \"{results.ModelVersion}\"");
            Debug.WriteLine("");

            foreach (AnalyzeSentimentResult result in results)
            {
                TextDocumentInput document = documents[i++];

                Debug.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\", Text=\"{document.Text}\"):");

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error: {result.Error.Code}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"Document sentiment is {result.DocumentSentiment.Sentiment}, with confidence scores: ");
                    Debug.WriteLine($"    Positive confidence score: {result.DocumentSentiment.ConfidenceScores.Positive}.");
                    Debug.WriteLine($"    Neutral confidence score: {result.DocumentSentiment.ConfidenceScores.Neutral}.");
                    Debug.WriteLine($"    Negative confidence score: {result.DocumentSentiment.ConfidenceScores.Negative}.");

                    Debug.WriteLine($"    Sentence sentiment results:");

                    foreach (SentenceSentiment sentenceSentiment in result.DocumentSentiment.Sentences)
                    {
                        Debug.WriteLine($"    Sentiment is {sentenceSentiment.Sentiment}, with confidence scores: ");
                        Debug.WriteLine($"        Positive confidence score: {sentenceSentiment.ConfidenceScores.Positive}.");
                        Debug.WriteLine($"        Neutral confidence score: {sentenceSentiment.ConfidenceScores.Neutral}.");
                        Debug.WriteLine($"        Negative confidence score: {sentenceSentiment.ConfidenceScores.Negative}.");
                    }

                    Debug.WriteLine($"    Document statistics:");
                    Debug.WriteLine($"        Character count (in Unicode graphemes): {result.Statistics.GraphemeCount}");
                    Debug.WriteLine($"        Transaction count: {result.Statistics.TransactionCount}");
                    Debug.WriteLine("");
                }
            }

            Debug.WriteLine($"Batch operation statistics:");
            Debug.WriteLine($"    Document count: {results.Statistics.DocumentCount}");
            Debug.WriteLine($"    Valid document count: {results.Statistics.ValidDocumentCount}");
            Debug.WriteLine($"    Invalid document count: {results.Statistics.InvalidDocumentCount}");
            Debug.WriteLine($"    Transaction count: {results.Statistics.TransactionCount}");
            Debug.WriteLine("");
        }
コード例 #8
0
        public void AnalyzeSentimentBatch()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            #region Snippet:TextAnalyticsSample2AnalyzeSentimentBatch
            string documentA = @"The food and service were unacceptable, but the concierge were nice.
                                After talking to them about the quality of the food and the process
                                to get room service they refunded the money we spent at the restaurant and
                                gave us a voucher for nearby restaurants.";

            string documentB = @"Nos hospedamos en el Hotel Foo la semana pasada por nuestro aniversario. La gerencia
                                sabía de nuestra celebración y me ayudaron a tenerle una sorpresa a mi pareja.
                                La habitación estaba limpia y decorada como yo había pedido. Una gran experiencia.
                                El próximo año volveremos.";

            string documentC = @"The rooms were beautiful. The AC was good and quiet, which was key for us as outside
                                it was 100F and our baby was getting uncomfortable because of the heat. The breakfast
                                was good too with good options and good servicing times.
                                The thing we didn't like was that the toilet in our bathroom was smelly.
                                It could have been that the toilet was not cleaned before we arrived.
                                Either way it was very uncomfortable. Once we notified the staff, they came and cleaned
                                it and left candles.";

            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", documentA)
                {
                    Language = "en",
                },
                new TextDocumentInput("2", documentB)
                {
                    Language = "es",
                },
                new TextDocumentInput("3", documentC)
                {
                    Language = "en",
                },
                new TextDocumentInput("4", string.Empty)
            };

            var options = new AnalyzeSentimentOptions {
                IncludeStatistics = true
            };

            Response <AnalyzeSentimentResultCollection> response = client.AnalyzeSentimentBatch(documents, options);
            AnalyzeSentimentResultCollection            sentimentPerDocuments = response.Value;

            int i = 0;
            Console.WriteLine($"Results of Azure Text Analytics \"Sentiment Analysis\" Model, version: \"{sentimentPerDocuments.ModelVersion}\"");
            Console.WriteLine("");

            foreach (AnalyzeSentimentResult sentimentInDocument in sentimentPerDocuments)
            {
                TextDocumentInput document = documents[i++];

                Console.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\"):");

                if (sentimentInDocument.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error: {sentimentInDocument.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {sentimentInDocument.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"Document sentiment is {sentimentInDocument.DocumentSentiment.Sentiment}, with confidence scores: ");
                    Console.WriteLine($"  Positive confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Positive}.");
                    Console.WriteLine($"  Neutral confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Neutral}.");
                    Console.WriteLine($"  Negative confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Negative}.");
                    Console.WriteLine("");
                    Console.WriteLine($"  Sentence sentiment results:");

                    foreach (SentenceSentiment sentimentInSentence in sentimentInDocument.DocumentSentiment.Sentences)
                    {
                        Console.WriteLine($"  For sentence: \"{sentimentInSentence.Text}\"");
                        Console.WriteLine($"  Sentiment is {sentimentInSentence.Sentiment}, with confidence scores: ");
                        Console.WriteLine($"    Positive confidence score: {sentimentInSentence.ConfidenceScores.Positive}.");
                        Console.WriteLine($"    Neutral confidence score: {sentimentInSentence.ConfidenceScores.Neutral}.");
                        Console.WriteLine($"    Negative confidence score: {sentimentInSentence.ConfidenceScores.Negative}.");
                        Console.WriteLine("");
                    }

                    Console.WriteLine($"  Document statistics:");
                    Console.WriteLine($"    Character count: {sentimentInDocument.Statistics.CharacterCount}");
                    Console.WriteLine($"    Transaction count: {sentimentInDocument.Statistics.TransactionCount}");
                }
                Console.WriteLine("");
            }

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"  Document count: {sentimentPerDocuments.Statistics.DocumentCount}");
            Console.WriteLine($"  Valid document count: {sentimentPerDocuments.Statistics.ValidDocumentCount}");
            Console.WriteLine($"  Invalid document count: {sentimentPerDocuments.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"  Transaction count: {sentimentPerDocuments.Statistics.TransactionCount}");
            #endregion
        }
コード例 #9
0
        public void AnalyzeSentimentBatchConvenience()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            #region Snippet:TextAnalyticsSample2AnalyzeSentimentConvenience
            string documentA = @"The food and service were unacceptable, but the concierge were nice.
                                After talking to them about the quality of the food and the process
                                to get room service they refunded the money we spent at the restaurant and
                                gave us a voucher for nearby restaurants.";

            string documentB = @"Nice rooms! I had a great unobstructed view of the Microsoft campus but bathrooms
                                were old and the toilet was dirty when we arrived. It was close to bus stops and
                                groceries stores.
                                If you want to be close to campus I will recommend it, otherwise, might be
                                better to stay in a cleaner one";

            string documentC = @"The rooms were beautiful. The AC was good and quiet, which was key for us as outside
                                it was 100F and our baby was getting uncomfortable because of the heat. The breakfast
                                was good too with good options and good servicing times.
                                The thing we didn't like was that the toilet in our bathroom was smelly.
                                It could have been that the toilet was not cleaned before we arrived.";

            string documentD = string.Empty;

            var documents = new List <string>
            {
                documentA,
                documentB,
                documentC,
                documentD
            };

            Response <AnalyzeSentimentResultCollection> response = client.AnalyzeSentimentBatch(documents);
            AnalyzeSentimentResultCollection            sentimentPerDocuments = response.Value;

            int i = 0;
            Console.WriteLine($"Results of \"Sentiment Analysis\" Model, version: \"{sentimentPerDocuments.ModelVersion}\"");
            Console.WriteLine("");

            foreach (AnalyzeSentimentResult sentimentInDocument in sentimentPerDocuments)
            {
                Console.WriteLine($"On document with Text: \"{documents[i++]}\"");
                Console.WriteLine("");

                if (sentimentInDocument.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error: {sentimentInDocument.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {sentimentInDocument.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"Document sentiment is {sentimentInDocument.DocumentSentiment.Sentiment}, with confidence scores: ");
                    Console.WriteLine($"  Positive confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Positive}.");
                    Console.WriteLine($"  Neutral confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Neutral}.");
                    Console.WriteLine($"  Negative confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Negative}.");
                    Console.WriteLine("");
                    Console.WriteLine($"  Sentence sentiment results:");

                    foreach (SentenceSentiment sentimentInSentence in sentimentInDocument.DocumentSentiment.Sentences)
                    {
                        Console.WriteLine($"  For sentence: \"{sentimentInSentence.Text}\"");
                        Console.WriteLine($"  Sentiment is {sentimentInSentence.Sentiment}, with confidence scores: ");
                        Console.WriteLine($"    Positive confidence score: {sentimentInSentence.ConfidenceScores.Positive}.");
                        Console.WriteLine($"    Neutral confidence score: {sentimentInSentence.ConfidenceScores.Neutral}.");
                        Console.WriteLine($"    Negative confidence score: {sentimentInSentence.ConfidenceScores.Negative}.");
                        Console.WriteLine("");
                    }
                }
                Console.WriteLine("");
            }
            #endregion
        }