File size: 1,719 Bytes
fcc36dd
c67a833
fcc36dd
c67a833
b67dd17
fcc36dd
c67a833
 
 
 
 
 
 
 
fcc36dd
c67a833
 
 
 
 
 
fcc36dd
c67a833
 
 
 
 
 
fcc36dd
 
 
c67a833
 
 
 
 
 
 
 
 
 
 
fcc36dd
c67a833
 
 
fcc36dd
 
 
c67a833
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
library(shiny)
library(readr)
library(dplyr)
library(sentimentr)
library(tidytext)

analyze_sentiment <- function(sentence) {
  sentence_df <- tibble(text = sentence)
  sentence_df <- unnest_tokens(sentence_df, input = text, output = word)
  nrc_sentiment <- sentiment(get_sentences(sentence_df), polarity_dt = lexicon::hash_sentiment_nrc,
                             valence_shifters_dt = lexicon::hash_valence_shifters)
  
  return(nrc_sentiment)
}

ui <- fluidPage(
  titlePanel("Sentiment Analysis App"),
  sidebarLayout(
    sidebarPanel(
      textInput("sentence_input", "Enter a sentence:", ""),
      actionButton("analyze_button", "Analyze")
    ),
    mainPanel(
      h4("Sentiment Score for the Whole Sentence:"),
      verbatimTextOutput("sentence_sentiment_output"),
      h4("Sentiment Score for Each Word:"),
      tableOutput("word_sentiment_output")
    )
  )
)

server <- function(input, output) {
  observeEvent(input$analyze_button, {
    sentence <- input$sentence_input
    sentiment_scores <- analyze_sentiment(sentence)
    
    # Calculate overall sentiment for the whole sentence
    sentence_sentiment <- mean(sentiment_scores$sentiment)
    sentence_sentiment_description <- ifelse(sentence_sentiment >= 0, "Positive", ifelse(sentence_sentiment == 0, "Neutral","Negative"))
    
    # Categorize sentiment for each word
    sentiment_scores$word_sentiment <- ifelse(sentiment_scores$sentiment > 0, "Positive", ifelse(sentiment_scores$sentiment == 0, "Neutral","Negative"))
    
    output$sentence_sentiment_output <- renderPrint(paste("Overall Sentiment:", sentence_sentiment_description))
    output$word_sentiment_output <- renderTable(sentiment_scores)
  })
}

shinyApp(ui, server)