我想根据R运行中的内部结果有条件地替换文本块。假设我将导入一个模板,例如teXt
:
lines <- tempfile(fileext = ".data")
cat("
We have a (positive)1 (negative)2 number.
", file=lines, sep = "\n")
teXt <- readLines(lines)
在本文中,我们有1阳性和2阴性的可能性。假设我尝试使用正数:
teXt <- stringr::str_replace_all(teXt, " (negative)2", "") ## Exclude negative string possibility
teXt <- stringr::str_replace_all(teXt, " (positive)1", "positive") ## make positive the word in the final text
但是,替换内容与我的预期不符,即未产生“我们有一个正数”的句子,并且没有保留原始模板文本。我尝试使用*words*
代替(words)
,但是也没有用。我想知道我们是否在R中具有函数以更智能(且可行!)的方式执行此类任务。
答案 0 :(得分:2)
要尝试工作,您必须转义特殊字符(左括号和右括号)
teXt <- stringr::str_replace_all(teXt, "\\(negative\\)2", "")
teXt <- stringr::str_replace_all(teXt, "\\(positive\\)1", "positive")
假设您有一个正数,一种简化的(?)方法是删除圆括号以及其中的文本,并用"positive"
代替。
stringr::str_replace_all(teXt, "\\(.*\\)\\d+", "positive")
#[1] "" " We have a positive number." " "
或在基数R中使用gsub
gsub("\\(.*\\)\\d+", "positive", teXt)
如果要删除前导空格和滞后空格,可以将输出包装在trimws
中。