コード例 #1
0
 /// <summary>
 ///     Updates the ngram usage count based on the sentiment and whether or not
 ///     the partialTweetText is a rewteet.
 /// </summary>
 /// <param name="ngram">The ngram.</param>
 /// <param name="isRetweet">
 ///     if set to <c>true</c> [is retweet].
 /// </param>
 /// <param name="sentiment">The sentiment.</param>
 public static void UpdateNgramUsageCount(NgramBase ngram, bool isRetweet, Sentiment sentiment)
 {
     if (isRetweet)
     {
         if (sentiment.Equals(Sentiment.Positive))
         {
             ngram.RtPositiveCount++;
         }
         else if (sentiment.Equals(Sentiment.Negative))
         {
             ngram.RtNegativeCount++;
         }
         else
         {
             ngram.RtNeutralCount++;
         }
     }
     else
     {
         if (sentiment.Equals(Sentiment.Positive))
         {
             ngram.PositiveCount++;
         }
         else if (sentiment.Equals(Sentiment.Negative))
         {
             ngram.NegativeCount++;
         }
         else
         {
             ngram.NeutralCount++;
         }
     }
 }
コード例 #2
0
        /// <summary>
        ///     Takes a partialTweetText, cleans it, breaks it into ngrams and stemmed ngrams.
        /// </summary>
        /// <param name="partialTweetText">The partialTweetText.</param>
        /// <param name="isRetweet">
        ///     if set to <c>true</c> [is retweet].
        /// </param>
        /// <param name="sentiment">The sentiment.</param>
        /// <param name="timestamp">The current time in UTC.</param>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="context">The context.</param>
        public static void ProcessTweetTextForCorpus(string partialTweetText,
                                                     bool isRetweet,
                                                     Sentiment sentiment,
                                                     DateTime timestamp,
                                                     IDictionary <String, String> dictionary,
                                                     IOclumenContext context)
        {
            // first let's grab the hashtags
            UpdateHashtagSentiment(partialTweetText, isRetweet, sentiment, timestamp, context);

            // clean up the partialTweetText a bit
            string cleanedTweet =
                new TextCleaner(partialTweetText).StripPunctuation().RemoveExcessSpaces().ToLower().ToString();


            IList <string> unigrams = NgramGenerator.GenerateNgrams(cleanedTweet, 1);
            IList <string> bigrams  = NgramGenerator.GenerateNgrams(cleanedTweet, 2);

            IList <string> stemmedNgrams  = StemNgram(unigrams, dictionary);
            IList <string> stemmedBigrams = StemNgram(bigrams, dictionary);

            UpdateNgramsSentiment(unigrams, isRetweet, sentiment, false, context.BasicNgrams, context);
            UpdateNgramsSentiment(bigrams, isRetweet, sentiment, false, context.BasicNgrams, context);
            UpdateNgramsSentiment(stemmedNgrams, isRetweet, sentiment, true, context.StemmedNgrams, context);
            UpdateNgramsSentiment(stemmedBigrams, isRetweet, sentiment, true, context.StemmedNgrams, context);
        }
コード例 #3
0
        public void AnalysisOfPhraseNeutralEmptyEntity()
        {
            management.AuthorManagement.AddAuthor(author);

            Sentiment sentiment = new Sentiment()
            {
                SentimientText = "Me encanta",
                SentimentType  = Sentiment.TypeSentiment.Positive
            };

            management.SentimentManagement.AddSentiment(sentiment);
            Phrase phrase = new Phrase()
            {
                TextPhrase   = "Me encanta",
                PhraseAuthor = author,
                PhraseDate   = DateTime.Now
            };

            management.PhraseManagement.AddPhrase(phrase);
            management.AnalysisPhrase(phrase);
            Phrase expectedPhrase = new Phrase()
            {
                TextPhrase   = "Me encanta",
                PhraseDate   = DateTime.Now,
                Entity       = null,
                PhraseType   = Phrase.TypePhrase.Neutral,
                PhraseAuthor = author
            };

            Assert.AreEqual(expectedPhrase, phrase);
        }
        internal bool ProcessTweet(string requestBody)
        {
            // This is where we will do our work

            try
            {
                Sentiment detectedSentiment = service.DetectSentiment(requestBody);

                switch (detectedSentiment)
                {
                case Sentiment.Positive:
                    Console.WriteLine($"The string {requestBody} has a Positive Sentiment.");
                    break;

                case Sentiment.Negetive:
                    Console.WriteLine($"The string {requestBody} has a Negative Sentiment.");
                    break;

                case Sentiment.Neutral:
                    Console.WriteLine($"The string {requestBody} has a Neautral Sentiment.");
                    break;
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
コード例 #5
0
        static void Main(string[] args)
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            //List<List<Tweet>> allTweets = new List<List<Tweet>>();

            Sentiment sentiment = new Sentiment();

            Console.WriteLine("done\n");

            List <Tweet> LifeTweets = Parser.GetTweets("my_life.txt");

            Console.WriteLine("done\n");
            //List<Tweet> JobTweets = Parser.GetTweets("my_job.txt");
            //Console.WriteLine("done\n");
            //List<Tweet> ObamaTweets = Parser.GetTweets("obama.txt");
            //Console.WriteLine("done\n");
            //List<Tweet> SandwichTweets = Parser.GetTweets("sandwich.txt");
            //Console.WriteLine("done\n");
            //List<Tweet> TexasTweets = Parser.GetTweets("texas.txt");
            //Console.WriteLine("done\n");

            Dictionary <string, List <List <List <double> > > > USA = Parser.GetRegions();

            Console.WriteLine("done\n");

            LifeTweets[1].CountWeight(sentiment);
            Console.WriteLine(LifeTweets[1].Weight + "\ndone\n");

            Console.ReadLine();
        }
        public void AddSentimentUpdatesPhrases()
        {
            PhraseRepository phraseRepository = new PhraseRepository();

            phraseRepository.Clear();

            AuthorRepository authorRepository = new AuthorRepository();

            authorRepository.Clear();

            authorRepository.Add(AUTHOR);

            Phrase    phrase    = new Phrase("i like google", DateTime.Now, AUTHOR);
            Sentiment sentiment = new Sentiment(SentimentType.POSITIVE, "i like");

            try
            {
                phraseRepository.Add(phrase);
            }
            catch (AnalysisException) { }

            try
            {
                REPOSITORY.Add(sentiment);
            }
            catch (AnalysisException) { }

            Assert.AreEqual(sentiment.Type, phraseRepository.Get(phrase.Id).Type);
        }
        public void DeleteSentimentUpdateAlarm()
        {
            Phrase phrase = new Phrase("i like google", DateTime.Now, AUTHOR);
            Entity google = new Entity("google");

            Sentiment sentiment = new Sentiment(SentimentType.POSITIVE, "i like");

            try
            {
                phrase.AnalyzePhrase(new List <Entity> {
                    google
                }, new List <Sentiment> {
                    sentiment
                });
            }
            catch (AnalysisException) { }

            EntityAlarm alarm = new EntityAlarm("1", "1", SentimentType.POSITIVE, google);

            REPOSITORY.Add(sentiment);

            REPOSITORY.Delete(sentiment.Id);

            Assert.AreEqual(alarm.PostCount, 0);
        }
コード例 #8
0
        /// <summary>
        ///     Updates the hashtag sentiment much in the same way general sentiment is recorded.
        /// </summary>
        /// <param name="tweetText">The tweet text.</param>
        /// <param name="isRetweet">
        ///     if set to <c>true</c> [is retweet].
        /// </param>
        /// <param name="sentiment">The sentiment.</param>
        /// <param name="timestamp">The timestamp.</param>
        /// <param name="context">The context.</param>
        public static void UpdateHashtagSentiment(string tweetText, bool isRetweet, Sentiment sentiment,
                                                  DateTime timestamp, IOclumenContext context)
        {
            // clean up a bit, we can't use the one for processing tweets due to wanting to keep punctuation
            // and we cant do that after because we would have to call remove excess spaces again anyways
            IList <string> hashtags =
                TwitterTextUtility.GetHashtags(new TextCleaner(tweetText).RemoveExcessSpaces().ToLower().ToString());

            foreach (string hashtag in hashtags)
            {
                HashtagNgram hashtagNgram = context.Hashtags.FirstOrDefault(x => x.Text == hashtag);

                // create the new ngram entity if it isn't in our database already
                if (hashtagNgram == null)
                {
                    hashtagNgram = new HashtagNgram
                    {
                        Cardinality = 1,
                        FirstSeen   = timestamp,
                        Text        = hashtag
                    };

                    context.Hashtags.Add(hashtagNgram);
                    context.SaveChanges();
                }

                UpdateNgramUsageCount(hashtagNgram, isRetweet, sentiment);
            }
        }
コード例 #9
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string sentimentText = textBoxSentiment.Text;

            if (IsCheckedType().Equals(Sentiment.TypeSentiment.Neutral))
            {
                labelError.Visible = true;
                labelError.Text    = "Debe seleccionar el tipo de sentimiento.";
            }
            else
            {
                try
                {
                    Sentiment sentiment = new Sentiment()
                    {
                        SentimientText = sentimentText,
                        SentimentType  = IsCheckedType()
                    };
                    generalManagement.SentimentManagement.AddSentiment(sentiment);
                    MessageBox.Show("Sentimiento agregado correctamente");
                    InitializeListOfSentiment();
                    ClearAllFields();
                    DisplayDeleteButton();
                }
                catch (SentimentManagementException exc)
                {
                    labelError.Visible = true;
                    labelError.Text    = exc.Message;
                }
                catch (Exception)
                {
                    MessageBox.Show("Error interno del sistema");
                }
            }
        }
コード例 #10
0
        public IActionResult Insert_Data(Sentiment ss)
        {
            int?status = null;

            if (ss.sentimentText != null)
            {
                Sentiment emp    = new Sentiment();
                var       result = db.create_sentiment(ss);

                if (result == "error")
                {
                    Response.StatusCode = 500;
                    status = -1;
                    return(NotFound());
                }
                else if (result == "exist")
                {
                    status = 0;
                    ModelState.AddModelError("", "Dữ liệu đã tồn tại"); //-sumary
                    return(RedirectToAction("Data", new { status = status, s = ss }));
                }
                else if (result == "success")
                {
                    status = 1;
                    return(RedirectToAction("Data", new { status = status }));
                }
            }
            return(RedirectToAction("Data", new { status = status, s = ss }));
        }
コード例 #11
0
        // POST: /Graph/search
        public JsonResult Search(string search)
        {
            try
            {
                IEnumerable <Tweetinvi.Models.ITweet> tweets = null;
                if (search != null)
                {
                    tweets = SearchTweets.Search(search, 1000);
                    foreach (var twit in tweets)
                    {
                        Models.Tweet T = new Models.Tweet();
                        T.tweet = twit;

                        T.sentiment = Sentiment.Analyse(twit.FullText);
                        list_of_tweets.Add(T);
                    }
                    Tweets instance = Tweets.getInstance();
                    instance.tweets     = list_of_tweets;
                    instance.searchTerm = search;
                    var temp = Json(Analysis.GetPackages(instance));
                    return(temp);
                }
                else
                {
                    return(Json("search is null"));
                };
            }
            catch (Exception e)
            {
                return(Json(e));
            }
        }
コード例 #12
0
        public void GetHighGrade()
        {
            Entity entity = new Entity("Starbucks");

            Sentiment iLike        = new Sentiment(SentimentType.POSITIVE, "I like");
            Sentiment iLove        = new Sentiment(SentimentType.POSITIVE, "I love");
            Sentiment fascinatesMe = new Sentiment(SentimentType.POSITIVE, "Fascinates me");

            List <Sentiment> sentiments = new List <Sentiment>();

            sentiments.Add(iLike);
            sentiments.Add(iLove);
            sentiments.Add(fascinatesMe);

            string word = "I love and fascinates me Starbucks, i like it to much";

            Phrase phrase = new Phrase(word, DateTime.Now, AUTHOR);

            phrase.AnalyzePhrase(new List <Entity>()
            {
                entity
            }, sentiments);

            Assert.AreEqual(phrase.Grade, SentimentGrade.HIGH);
        }
コード例 #13
0
ファイル: SentimentService.cs プロジェクト: Drelnoch/Mute
        public SentimentResult(string message, float negative, float positive, float neutral, TimeSpan time)
        {
            Text               = message;
            NegativeScore      = negative;
            PositiveScore      = positive;
            NeutralScore       = neutral;
            ClassificationTime = time;

            ClassificationScore = Math.Max(negative, Math.Max(positive, neutral));

            // ReSharper disable CompareOfFloatsByEqualityOperator
            if (ClassificationScore == negative)
            {
                Classification = Sentiment.Negative;
            }
            else if (ClassificationScore == positive)
            {
                Classification = Sentiment.Positive;
            }
            else
            {
                Classification = Sentiment.Neutral;
            }
            // ReSharper restore CompareOfFloatsByEqualityOperator
        }
コード例 #14
0
        public void SetUp()
        {
            CleanRepositories();

            AUTHOR = new Author("sada", "sadasd", "sdaasd", new DateTime(1995, 2, 3));

            Entity google    = new Entity("Google");
            Entity starbucks = new Entity("Starbucks");

            ENTITITES = new List <Entity>();
            ENTITITES.Add(google);
            ENTITITES.Add(starbucks);

            Sentiment positive = new Sentiment(SentimentType.POSITIVE, "i like");
            Sentiment negative = new Sentiment(SentimentType.NEGATIVE, "i dont like");

            SENTIMENTS = new List <Sentiment>();
            SENTIMENTS.Add(positive);
            SENTIMENTS.Add(negative);

            PHRASE = new Phrase("I like Google", DateTime.Now, AUTHOR);

            ALARM  = new EntityAlarm("1", "1", SentimentType.POSITIVE, google);
            ALARMS = new List <EntityAlarm>();
            ALARMS.Add(ALARM);

            REPOSITORY = new PhraseRepository();
        }
コード例 #15
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,pos,compound,neu,neg,HeadLineId")] Sentiment sentiment)
        {
            if (id != sentiment.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(sentiment);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SentimentExists(sentiment.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["HeadLineId"] = new SelectList(_context.HeadLines, "Id", "Id", sentiment.HeadLineId);
            return(View(sentiment));
        }
        public void DeleteThreeSentimentPositive1()
        {
            Sentiment sentiment = new Sentiment()
            {
                SentimientText = "Me gusta",
                SentimentType  = Sentiment.TypeSentiment.Positive
            };
            Sentiment sentiment2 = new Sentiment()
            {
                SentimientText = "Me encanta",
                SentimentType  = Sentiment.TypeSentiment.Positive
            };
            Sentiment sentiment3 = new Sentiment()
            {
                SentimientText = "Lo amo",
                SentimentType  = Sentiment.TypeSentiment.Positive
            };
            Sentiment sentiment4 = new Sentiment()
            {
                SentimientText = "Es precioso",
                SentimentType  = Sentiment.TypeSentiment.Positive
            };

            manegement.AddSentiment(sentiment);
            manegement.AddSentiment(sentiment2);
            manegement.AddSentiment(sentiment3);
            manegement.AddSentiment(sentiment4);
            manegement.DeleteSentiment(sentiment2);
            manegement.DeleteSentiment(sentiment3);
            manegement.DeleteSentiment(sentiment);

            CollectionAssert.Contains(manegement.AllSentiments, sentiment4);
        }
コード例 #17
0
        public void ToStringTest()
        {
            string    str       = string.Format("{0} - [{1}]", WORD, SentimentType.POSITIVE.ToString());
            Sentiment sentiment = new Sentiment(SentimentType.POSITIVE, WORD);

            Assert.AreEqual(sentiment.ToString(), str);
        }
コード例 #18
0
        private void LoadData(Sentiment sentiment)
        {
            CleanMessage();

            txtWord.Text = sentiment.Word;
            cboSentimentType.SelectedItem = sentiment.Type;
        }
コード例 #19
0
        private void CleanFields()
        {
            SelectedSentiment = null;

            txtWord.Text = string.Empty;
            lstSentiments.ClearSelected();
        }
コード例 #20
0
        private void btnSave_Click(object sender, System.EventArgs e)
        {
            try
            {
                string message;

                Sentiment sentiment = new Sentiment((SentimentType)cboSentimentType.SelectedItem, txtWord.Text);

                if (SelectedSentiment == null)
                {
                    repository.Add(sentiment);
                    message = SAVE_SENTIMENT;
                }
                else
                {
                    sentiment.Id = SelectedSentiment.Id;
                    repository.Modify(SelectedSentiment.Id, sentiment);
                    message = MODIFY_SENTIMENT;
                }

                LoadSentiments();
                ShowSuccess(message);
                CleanFields();
            }
            catch (SentimentException ex)
            {
                ShowError(ex.Message);
            }
        }
コード例 #21
0
        private Response RateItem(string name, Sentiment sentiment)
        {
            if (String.IsNullOrWhiteSpace(name))
            {
                return(new Response().WithStatusCode(HttpStatusCode.InternalServerError));
            }

            try
            {
                string voteName = "lastvote_" + name.Dehumanize();
                var    lastVote = Request.Session[voteName];

                if (lastVote != null)
                {
                    TimeSpan voteLimit = new TimeSpan(0, 5, 0);
                    TimeSpan remaining = voteLimit - (((DateTime)lastVote) - DateTime.Now);

                    if (((DateTime)lastVote) - DateTime.Now <= voteLimit)
                    {
                        return(Response.AsText(remaining.Humanize()).WithStatusCode(HttpStatusCode.TooManyRequests));
                    }
                }
                Request.Session[voteName] = DateTime.Now;

                MenuDbRepository.Current.ChangeRating(name, sentiment);
                return(Response.AsJson(MenuDbRepository.Current.GetRatingForItem(name)).WithStatusCode(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                this.Log().Error("Could not rate item " + name, ex);
                return(new Response().WithStatusCode(HttpStatusCode.InternalServerError));
            }
        }
コード例 #22
0
        /// <summary>
        /// Build entity sentiment result in bson document format
        /// </summary>
        /// <param name="articleId">ObjectId of the article</param>
        /// <param name="entities">List of entities</param>
        /// <returns>Entity sentiment result in BsonDocument</returns>
        public static BsonDocument BuildSentimentBsonDocument(BsonDocument article, Sentiment overallSentiment, List <Entity> entities, List <ClassificationCategory> categories)
        {
            // Convert overall sentiment to BsonDocument
            var bsonOverallSentiment = overallSentiment.ToBsonDocument();

            // Convert list of entities -> JSON -> BsonDocument
            var jsonEntities = $"{{ Entities: {JsonConvert.SerializeObject(entities)} }}";
            var bsonEntities = BsonDocument.Parse(jsonEntities);

            // Convert list of categories -> JSON -> BsonDocument
            var jsonCategories = $"{{ Categories: {JsonConvert.SerializeObject(categories)} }}";
            var bsonCategories = BsonDocument.Parse(jsonCategories);

            //Create Sentiment Bson Doc
            BsonDocument sentimentDoc = new BsonDocument
            {
                { "News", article },
                { "OverallSentiment", bsonOverallSentiment },
            };

            sentimentDoc.AddRange(bsonEntities);
            sentimentDoc.AddRange(bsonCategories);
            sentimentDoc.Add("AnalyzedAt", DateTime.Now);

            return(sentimentDoc);
        }
コード例 #23
0
ファイル: HomeModule.cs プロジェクト: jmazouri/Daventinder
        private Response RateItem(string name, Sentiment sentiment)
        {
            if (String.IsNullOrWhiteSpace(name)) { return new Response().WithStatusCode(HttpStatusCode.InternalServerError); }

            try
            {
                string voteName = "lastvote_" + name.Dehumanize();
                var lastVote = Request.Session[voteName];

                if (lastVote != null)
                {
                    TimeSpan voteLimit = new TimeSpan(0, 5, 0);
                    TimeSpan remaining = voteLimit - (((DateTime)lastVote) - DateTime.Now);

                    if (((DateTime)lastVote) - DateTime.Now <= voteLimit)
                    {
                        return Response.AsText(remaining.Humanize()).WithStatusCode(HttpStatusCode.TooManyRequests);
                    }
                }
                Request.Session[voteName] = DateTime.Now;

                MenuDbRepository.Current.ChangeRating(name, sentiment);
                return Response.AsJson(MenuDbRepository.Current.GetRatingForItem(name)).WithStatusCode(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                this.Log().Error("Could not rate item " + name, ex);
                return new Response().WithStatusCode(HttpStatusCode.InternalServerError);
            }
        }
 private void VerifyFormatAdd(Sentiment sentiment)
 {
     if (IsPartOfAnotherSentiment(sentiment))
     {
         throw new SentimentManagementException(MessagesExceptions.ErrorIsContained);
     }
 }
 void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("sentiment");
     writer.WriteStringValue(Sentiment.ToSerialString());
     writer.WritePropertyName("confidenceScores");
     writer.WriteObjectValue(ConfidenceScores);
     writer.WritePropertyName("sentences");
     writer.WriteStartArray();
     foreach (var item in Sentences)
     {
         writer.WriteObjectValue(item);
     }
     writer.WriteEndArray();
     writer.WritePropertyName("id");
     writer.WriteStringValue(Id);
     writer.WritePropertyName("warnings");
     writer.WriteStartArray();
     foreach (var item in Warnings)
     {
         writer.WriteObjectValue(item);
     }
     writer.WriteEndArray();
     if (Optional.IsDefined(Statistics))
     {
         writer.WritePropertyName("statistics");
         writer.WriteObjectValue(Statistics.Value);
     }
     writer.WriteEndObject();
 }
 private void VerifyFormatDelete(Sentiment sentiment)
 {
     if (IsNotContained(sentiment))
     {
         throw new SentimentManagementException(MessagesExceptions.ErrorDontExist);
     }
 }
        public void ModifySentimentNotUpdatePhraseWithoutType()
        {
            PhraseRepository phraseRepository = new PhraseRepository();
            AuthorRepository authorRepository = new AuthorRepository();

            Phrase    phrase    = new Phrase("i like google", DateTime.Now, AUTHOR);
            Sentiment sentiment = new Sentiment(SentimentType.POSITIVE, "i love");

            authorRepository.Add(AUTHOR);

            try
            {
                REPOSITORY.Add(sentiment);
            }
            catch (AnalysisException) { }

            try
            {
                phraseRepository.Add(phrase);
            }
            catch (AnalysisException) { }

            SENTIMENT.Word = "i dont like";
            SENTIMENT.Type = SentimentType.NEGATIVE;

            REPOSITORY.Modify(sentiment.Id, SENTIMENT);

            Assert.IsNull(phraseRepository.Get(phrase.Id).Type);
        }
 public void AddSentiment(Sentiment sentiment)
 {
     sentiment.VerifyFormat();
     VerifyFormatAdd(sentiment);
     sentiment.SentimientText = Utilities.DeleteSpaces(sentiment.SentimientText).Trim();
     sentimentPersistence.AddSentiment(sentiment);
 }
コード例 #29
0
        public void OnNext(Payload twitterPayloadData)
        {
            try
            {
                Push(twitterPayloadData.SentimentScore);

                var sentiment = new Sentiment
                {
                    Timestamp = twitterPayloadData.CreatedAt,
                    Value     = _scores.Average()
                };

                if (_logger.IsEnabled(LogLevel.Trace))
                {
                    var message = JsonConvert.SerializeObject(sentiment, Formatting.Indented);
                    Console.WriteLine("Broadcasting Sentiment to Clients ({0})", message);
                }

                _hubConnection.InvokeAsync("Broadcast", "sentiment", sentiment, _cancellationToken);
            }
            catch (Exception e)
            {
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
コード例 #30
0
        public static async Task <Sentiment> Execute(string text)
        {
            try
            {
                string url = $"https://gateway-a.watsonplatform.net/calls/text/TextGetTextSentiment?apikey={BotConfiguration.ALCHEMY_API_KEY}&text={text}&outputMode=json";

                string response = await s_httpClient.UploadStringTaskAsync(url, "");

                SentimentObject body;
                using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(response)))
                    body = Utils.Deserialize <SentimentObject>(stream);

                double score = 0;
                double min   = -0.5d;
                if (!string.IsNullOrEmpty(body.docSentiment.score))
                {
                    score = double.Parse(body.docSentiment.score);
                }

                Sentiment sent = (Sentiment)Enum.Parse(typeof(Sentiment), body.docSentiment.type);
                if (sent == Sentiment.negative && score > min)
                {
                    return(Sentiment.neutral);
                }

                return(sent);
            }
            catch (Exception)
            {
                return(Sentiment.neutral);
            }
        }
        public void DeleteThreeNegativesSentiments1()
        {
            Sentiment sentiment = new Sentiment()
            {
                SentimientText = "Lo odio",
                SentimentType  = Sentiment.TypeSentiment.Negative
            };
            Sentiment sentiment2 = new Sentiment()
            {
                SentimientText = "Lo detesto",
                SentimentType  = Sentiment.TypeSentiment.Negative
            };
            Sentiment sentiment3 = new Sentiment()
            {
                SentimientText = "Es nefasto",
                SentimentType  = Sentiment.TypeSentiment.Negative
            };
            Sentiment sentiment4 = new Sentiment()
            {
                SentimientText = "De lo peor",
                SentimentType  = Sentiment.TypeSentiment.Negative
            };

            manegement.AddSentiment(sentiment);
            manegement.AddSentiment(sentiment2);
            manegement.AddSentiment(sentiment3);
            manegement.AddSentiment(sentiment4);
            manegement.DeleteSentiment(sentiment2);
            manegement.DeleteSentiment(sentiment3);
            manegement.DeleteSentiment(sentiment);
            CollectionAssert.Contains(manegement.AllSentiments, sentiment4);
        }
コード例 #32
0
 public void ChangeRating(string menuItem, Sentiment sentiment)
 {
     if ((bool) _conn.ExecuteScalar(@"SELECT EXISTS(SELECT 1 FROM ratings WHERE MEAL = @a)", new {a = menuItem}))
     {
         _conn.Execute(
             sentiment == Sentiment.Positive
                 ? @"UPDATE ratings SET UPVOTES = UPVOTES + 1 WHERE MEAL = @a"
                 : @"UPDATE ratings SET DOWNVOTES = DOWNVOTES + 1 WHERE MEAL = @a", new {a = menuItem});
     }
     else
     {
         _conn.Execute(@"INSERT INTO ratings(MEAL, UPVOTES, DOWNVOTES) VALUES (@a, @b, @c)", new
         {
             a = menuItem,
             b = (sentiment == Sentiment.Positive ? 1 : 0),
             c = (sentiment == Sentiment.Negative ? 1 : 0)
         });
     }
 }
コード例 #33
0
ファイル: Result.cs プロジェクト: bfdill/SentimentAnalysis
 protected Result(bool success, string error, Sentiment sentiment)
 {
     Success = success;
     Error = error;
     Sentiment = sentiment;
 }
コード例 #34
0
 private ViveknResult(decimal confidence, bool success, string error, Sentiment sentiment)
     : base(success, error, sentiment)
 {
     Confidence = confidence;
 }
コード例 #35
0
 private AzureMachineLearningResult(decimal score, bool success, string error, Sentiment sentiment)
     : base(success, error, sentiment)
 {
     Score = score;
 }
コード例 #36
0
 public static Result Build(decimal score, Sentiment sentiment)
 {
     return new AzureMachineLearningResult(score, true, null, sentiment);
 }
コード例 #37
0
 public static Result Build(decimal confidence, Sentiment sentiment)
 {
     return new ViveknResult(confidence, true, null, sentiment);
 }