在R中为突出显示的单词列表突出显示文本的颜色

问题描述 投票:2回答:3

假设我有一系列文件,例如:

text = c("is it possible to highlight text for some words" , 
      "suppose i want words like words to be red and words like text to be blue")

我想知道是否可以使用R来突出显示具有预定义单词列表的颜色的文档(特别是对于大型语料库)。列表中的每个单词将获得特定颜色。例如,将“单词”突出显示为红色,将“text”突出显示为蓝色,如下所示。

enter image description here

r text highlight word
3个回答
3
投票

对于这个问题,这是一个有点hackish解决方案,并且对于大型语料库而言不是很可扩展。我很想知道是否有更简约,优雅和可扩展的方式来做到这一点。

library(tidyverse)
library(crayon)

# define text
text <- c("is it possible to highlight text for some words" , 
         "suppose i want words like words to be red and words like text to be blue")

# individuate words
unique_words <- function(x) {
  purrr::map(.x = x,
             .f = ~ unique(base::strsplit(x = ., split = " ")[[1]],
                           collapse = " "))
}

# creating a dataframe with crayonized text
df <- 
  tibble::enframe(unique_words(x = text)) %>%
  tidyr::unnest() %>%
# here you can specify the color/word combinations you need 
  dplyr::mutate(.data = .,
                value2 = dplyr::case_when(value == "text" ~ crayon::blue(value),
                                          value == "words" ~ crayon::red(value),
                TRUE ~ value)) %>%
  dplyr::select(., -value) 

# printing the text
print(cat(df$value2))

enter image description here

附:不幸的是,reprex无法使用彩色文本,因此无法生成完整的代表。


1
投票

这是完整调试的应用程序代码!

首先,需要的库:

library(shiny)
library(tidyverse)
library(DT)
library(magrittr)

然后,添加HTML标记的函数:

wordHighlight <- function(SuspWord,colH = 'yellow') {
  paste0('<span style="background-color:',colH,'">',SuspWord,'</span>')
}

现在UI部分:

ui <- fluidPage(
   titlePanel("Text Highlighting"),
   sidebarLayout(
      sidebarPanel(
        textInput("wordSearch", "Word Search")
      ),
    mainPanel(
        DT::dataTableOutput("table")
      )   
   )  
   )

最后,在服务器端:

server <- function(input, output) {
   sentence <- "The term 'data science' (originally used interchangeably with 'datalogy') has existed for over thirty years and was used initially as a substitute for computer science by Peter Naur in 1960."
   sentence2 = "One of the things we will want to do most often for social science analyses of text data is generate a document-term matrix."
   YourData = data.frame(N = c('001','002'), T = c(sentence,sentence2), stringsAsFactors=FALSE)
   highlightData <- reactive({
     if (input$wordSearch!="")
      {
        patterns = input$wordSearch
        YourData2 = YourData
        YourData2[,2] %<>% str_replace_all(regex(patterns, ignore_case = TRUE), wordHighlight)
        return(YourData2)
      }
    return(YourData)
  })
    output$table <- DT::renderDataTable({
      data <- highlightData() 
    }, escape = FALSE)
}

运行应用程序:

shinyApp(ui = ui, server = server)

0
投票

Indrajeet的答案很棒。这是基于Indrajeet答案的答案,只是一点点改变。

unique_words <- lapply(strsplit(text, " "), function(x){x[!x ==""]})

# creating a dataframe with crayonized text
df <- 
  tibble::enframe(unique_words) %>%
  tidyr::unnest() %>%

# here you can specify the color/word combinations you need 
dplyr::mutate(.data = .,
            value2 = dplyr::case_when(value == "text" ~ crayon::blue(value),
                                      value == "words" ~ crayon::red(value),
                                      TRUE ~ value)) %>%
dplyr::select(., -value) 

enter image description here

将输出放在两个不同的行(Collapse text by group in data frame)中:

df <- data.table(df)
df <- df[, list(text = paste(value2, collapse=" ")), by = name]

enter image description here

如果我想在R控制台中打印它,答案看起来很好。如果我想在R shinyapp中获得输出,它是如何工作的?

寻找其他替代方案并感谢您的帮助。

© www.soinside.com 2019 - 2024. All rights reserved.