简体   繁体   English

如何在 R Shiny 应用程序中呈现有选择的彩色文本?

[英]How can I render selectively colored text in an R Shiny app?

I have a shiny app with a tab in which users can upload their resume.我有一个闪亮的应用程序,带有一个选项卡,用户可以在其中上传他们的简历。 I'm using AI to extract skills from the resume, and I would like to render the text from their resume with the skills in a different color from the rest of the text.我正在使用 AI 从简历中提取技能,我想用与其余文本不同颜色的技能从他们的简历中呈现文本。

The closest I have gotten so far was by asking chatGPT, go figure.到目前为止,我最接近的是通过询问 chatGPT,去看看。 He/she/it gave me this "solution":他/她/它给了我这个“解决方案”:

library(shiny)
library(stringi)

highlight_keywords <- function(text, keywords) {
  for (keyword in keywords) {
    text <- stri_replace_all_fixed(text, keyword, 
                               paste0("<span style='color:red'>", keyword, "</span>"),    vectorize_all = FALSE)
  }
  return(text)
}

ui <- fluidPage(
  textInput("text", "Text"),
  textInput("keywords", "Keywords"),
  textOutput("text")
)

server <- function(input, output) {
  output$text <- renderText({
    highlight_keywords(input$text, strsplit(input$keywords, ",")[[1]])
  })
}

shinyApp(ui, server)`

But what is actually rendered is the input text in black with the html tags in plain text - eg:但实际呈现的是黑色的输入文本和纯文本的 html 标签 - 例如:

"I have a background in data science and over five years of hands-on experience conducting complex statistical analyses and building and deploying machine learning models" “我拥有数据科学背景,并且在执行复杂统计分析以及构建和部署机器学习模型方面拥有超过五年的实践经验”

Does anyone know why this is happening or how to accomplish what I am trying to accomplish?有谁知道为什么会这样或如何完成我想要完成的事情?

Thanks in advance!提前致谢!

The issue is that by default all HTML in a string is escaped and hence gets rendered as text.问题是默认情况下,字符串中的所有 HTML 都被转义,因此呈现为文本。 To prevent that you have to wrap your text in HTML() and switch from textOutput to eg htmlOutput .为防止您必须将文本包装在HTML()中并从textOutput切换到例如htmlOutput

library(shiny)
library(stringi)

highlight_keywords <- function(text, keywords) {
  for (keyword in keywords) {
    text <- stri_replace_all_fixed(
      text, keyword,
      paste0("<span style='color:red'>", keyword, "</span>"),
      vectorize_all = FALSE
    )
  }
  return(text)
}

ui <- fluidPage(
  textInput("text", "Text"),
  textInput("keywords", "Keywords"),
  htmlOutput("text")
)

server <- function(input, output) {
  output$text <- renderText({
    text_high <- highlight_keywords(input$text, strsplit(input$keywords, ",")[[1]])
    HTML(text_high)
  })
}

shinyApp(ui, server)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM