如何将html标记添加到vector中,以保留大写字母? 我的任务

如何将html标记添加到vector中,以保留大写字母? 我的任务,r,R,我需要在R中的字符串中向特定单词(每次)添加HTML标记,以使大写字母保持大写 我的尝试 第一种方法识别所有单词,但替换后的字符串中包含小写字母,所有字母也都是小写字母: x = "Some random text with some, issues" gsub(pattern = "some", replacement = "<>some<>", x = x, ignore.case = TRUE) x=“一

我需要在R中的字符串中向特定单词(每次)添加HTML标记,以使大写字母保持大写

我的尝试 第一种方法识别所有单词,但替换后的字符串中包含小写字母,所有字母也都是小写字母:

x = "Some random text with some, issues"
gsub(pattern = "some", replacement = "<>some<>", x = x, ignore.case = TRUE)
x=“一些随机文本,有些问题”
gsub(pattern=“some”,replacement=“some”,x=x,ignore.case=TRUE)
[1]“一些随机文本带有一些问题”
在某个地方,我发现了另一种使用函数的方法,该函数保留大写字母,但不识别逗号或点所对应的单词(在本例中,标记仅添加到第一个“some”中):


tagger也许这就是你想要的:

tagger[1]“一些随机文本带有一些问题”

您可以通过以下方式避免标记中的逗号:
gsub(pattern=paste0(“(”,word“)(\\,“\\”)?”),replacement=paste0(tag“\\1”,tag“\\2”),x=x,ignore.case=TRUE)
替换中的
“\\1”
“\\2”
是什么意思?这些是占位符。在正则表达式中使用parantises,我们创建了一个所谓的捕获组。“\\1”指第一组“\\2”指第二组。。。在替换过程中,占位符随后被替换为匹配的值,即“\\1”被替换为
单词“
=”(单词)”,“\\2”被替换为可选的“,”(,| \\)?”@MarBlo谢谢。我忽略了这一点。我认为理想的结果应该包括标签中的“,”。最佳S。
[1] "<>some<> random text with <>some<>, issues"
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] "<>Some<> random text with <>some<>, issues"

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