是否有 R 函数(或任何方式)对单个字符串中的所有数值进行颜色编码?

问题描述 投票:0回答:1

我成功地对字符串中的某些单词进行了颜色编码。

但是,我无法对同一字符串中的所有数值进行颜色编码。

我希望字符串中的所有数值(例如:1、2.3、4、6.87)具有相同的颜色(例如:蓝色)

我洗耳恭听任何解决方案,非常感谢您的帮助。

library(tidyverse)
library(crayon)
library(stringr)
library(readr)

# creating the string/vector # ALL GOOD HERE

text <- tolower(c("Kyste simple inférieur de
56 mm. Aorto-bi-iliaque en
5,9cm. Artères communes de 19mm et
de 87mm. 120mm stable.")) #tolower is removing capital letters#

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

# creating a dataframe with crayonized text # ALL SEEMS GOOD HERE #
df <- 
tibble::enframe(unique_words(x = text)) %>%
tidyr::unnest() %>%

# here you can specify the color/word combinations you need # PROBLEM SEEMS TO BE HERE #
dplyr::mutate(.data = .,
            value2 = dplyr::case_when(value == "aorto-bi-iliaque" ~ crayon::green(value),                                       
                                    value == gsub(".*(\\b\\d+\\b).*", "\\1", text) ~          crayon::blue(value), **# Here is where I need help #**
    TRUE ~ value)) %>%
dplyr::select(., -value) 


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

enter image description here

这就是它给我的,单词的颜色编码正确,但所有数值仍然不变

string colors extract numeric stringr
1个回答
0
投票

看起来你想要这样的东西:

unique_words <- function(x) {
    map(.x = x,
        .f = ~ unique(base::strsplit(x = ., split = " |\n")[[1]],
                        collapse = " "))
}

df <- enframe(unique_words(x = text)) %>%
    unnest(value) %>%
    mutate(value2 = case_when(value == "aorto-bi-iliaque" ~ green(value),                               
                              grepl(pattern = "\\d+", x = value) ~  str_replace_all(value, "([0-9\\,\\.])", blue("\\1")),
                              TRUE ~ value)) %>%
    select(., -value) 


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

输出:

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