r - 如何将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"
解决方案
也许这就是你正在寻找的:
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"
推荐阅读
- sql - 有没有办法在 SQL 中查找具有正向序列值的列?
- python - python是否使用其他方法保留注释顺序?
- c++ - 我在使用 mobaXterm 时遇到问题。下面的程序不断收到错误:
- android - 使用 Firebase Auth 在 Android 中获取 refreshToken 属性
- docker - Apache camel:使用 docker 进行测试基础设施
- c - 我需要帮助理解 C 中的头文件
- android - 转到另一个应用程序后如何自动恢复视频?
- c++ - 为什么打印时我的 qForm 变量 -nan
- javascript - discord.js 使用具有权限覆盖的频道创建公会
- aws-cloudwatch-log-insights - CloudWatch 记录见解 strcontains 不起作用