anantpinak33's picture
Update app.R
b67dd17
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)