【发布时间】:2015-04-05 22:25:30
【问题描述】:
基于我之前提出的两个问题:
R: How to prevent memory overflow when using mgsub in vector mode?
我确实喜欢 @Tyler 关于使用 fixed=TRUE 的建议,因为它显着加快了计算速度。但是,它并不总是适用。我需要将caps 替换为一个独立的单词,不带或不带标点符号。先验不知道可以在单词之后或之前做什么,但它必须是任何常规标点符号(,。! - + 等)。它不能是数字或字母。下面的例子。 capsule 必须保持原样。
i = "Here is the capsule, caps key, and two caps, or two caps. or even three caps-"
orig = "caps"
change = "cap"
gsub_FixedTrue <- function(i) {
i = paste0(" ", i, " ")
orig = paste0(" ", orig, " ")
change = paste0(" ", change, " ")
i = gsub(orig,change,i,fixed=TRUE)
i = gsub("^\\s|\\s$", "", i, perl=TRUE)
return(i)
}
#Second fastest, doesn't clog memory
gsub_FixedFalse <- function(i) {
i = gsub(paste0("\\b",orig,"\\b"),change,i)
return(i)
}
print(gsub_FixedTrue(i)) #wrong
print(gsub_FixedFalse(i)) #correct
结果。需要第二个输出
[1] "Here is the capsule, cap key, and two caps, or two caps. or even three caps-"
[1] "Here is the capsule, cap key, and two cap, or two cap. or even three cap-"
【问题讨论】:
-
究竟是什么问题?您希望能够将
fixed=TRUE与不固定的模式一起使用吗?它不是那样工作的。或者您正在尝试创建与非固定表达式等效的固定表达式?正则表达式的全部意义在于,这样的匹配对于固定字符串来说是乏味的。 -
好吧,我希望有一种方法可以快速去除逗号或句号,使用
gsub和fixed=TRUE将逗号缝合回更改后的单词。我对所有其他情况都有解决方案