【问题标题】:R: gsub with fixed=T or F and special casesR:gsub 固定=T 或 F 和特殊情况
【发布时间】:2015-04-05 22:25:30
【问题描述】:

基于我之前提出的两个问题:

R: How to prevent memory overflow when using mgsub in vector mode?

gsub speed vs pattern length

我确实喜欢 @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 与不固定的模式一起使用吗?它不是那样工作的。或者您正在尝试创建与非固定表达式等效的固定表达式?正则表达式的全部意义在于,这样的匹配对于固定字符串来说是乏味的。
  • 好吧,我希望有一种方法可以快速去除逗号或句号,使用gsubfixed=TRUE 将逗号缝合回更改后的单词。我对所有其他情况都有解决方案

标签: regex r gsub


【解决方案1】:

使用您之前问题中的部分进行测试,我认为我们可以在标点符号前面放置一个占位符,如下所示,而不会太慢:

line <- c("one", "two one", "four phones", "and a capsule", "But here's a caps key",
    "Here is the capsule, caps key, and two caps, or two caps. or even three caps-" )
e <- c("one", "two", "caps")
r <- c("ONE", "TWO", "cap")


line <- rep(line, 1700000/length(line))

line <- gsub("([[:punct:]])", " <DEL>\\1<DEL> ", line, perl=TRUE)

## Start    
line2 <- paste0(" ", line, " ")
e2 <-  paste0(" ", e, " ")
r2 <- paste0(" ", r, " ")


for (i in seq_along(e2)) {
    line2 <- gsub(e2[i], r2[i], line2, fixed=TRUE)
}

gsub("^\\s|\\s$| <DEL>|<DEL> ", "", line2, perl=TRUE)

【讨论】:

  • 谢谢!我将在我正在使用的真实数据上进行尝试,并使用“fixed = FALSE”获得已知结果。
  • 泰勒,你是天才!!这行得通!非常感谢。我可以添加一个建议来执行 ` i \\1 ", i, perl=TRUE)` 和 ` i = gsub ("^\\s|\\s$| | ", "", i, perl=TRUE) ` 处理-caps,之类的情况
  • 有道理,您可以添加为编辑(如果您有必要这样做;如果没有,我会添加它)。很高兴它有帮助。
  • 我可能没有足够的积分 - 尝试但没有奏效。再次感谢你! 技巧很棒!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 2015-10-21
  • 2021-04-04
  • 1970-01-01
  • 2012-07-13
  • 2016-05-16
相关资源
最近更新 更多