首页 > 解决方案 > 如何将html标签添加到R中的矢量保持大写字母?

问题描述

我的任务

我需要以大写字母保持大写的方式将 HTML 标记添加到 R 中的字符串中的特定单词(每个场合)。

我的尝试

第一种方法识别所有单词,但由于替换在结果字符串中包含小写字母,所有字母也是小写字母:

x = "Some random text with some, issues"
gsub(pattern = "some", replacement = "<>some<>", x = x, ignore.case = TRUE)
[1] "<>some<> random text with <>some<>, issues"

在某处,我发现了一种替代方法,该方法使用保留大写字母但不识别逗号或点伴随的单词的函数(在此示例中,标记仅添加到第一个“some”):

tagger <- function(text, word, tag) {
  x <- unlist(strsplit(text, split = " ", fixed = TRUE))
  x[tolower(x) == tolower(word)] <- paste0(tag,
                                            x[tolower(x) == tolower(word)],
                                            tag)
  paste(x, collapse = " ")
  
}

tagger(text = x, word = "some", tag = "<>")
[1] "<>Some<> random text with some, issues"

期望的结果

我怎样才能得到一个看起来像 1 或 2 的字符串?

[1] "<>Some<> random text with <>some<>, issues"

[2] "<>Some<> random text with <>some,<> issues"

标签: r

解决方案


也许这就是你正在寻找的:

tagger <- function(text, word, tag) {
  gsub(pattern = paste0("(", word, ")(\\.|,)?"), replacement = paste0(tag, "\\1\\2", tag), x = text, ignore.case = TRUE)
}

x <- "Some random text with some, issues"

tagger(x, "some", "<>")
#> [1] "<>Some<> random text with <>some,<> issues"

推荐阅读