【问题标题】:R strsplit() with multiple criteria [duplicate]具有多个条件的 R strsplit() [重复]
【发布时间】:2016-09-05 06:14:17
【问题描述】:

我正在尝试根据不同的标准拆分句子。我希望在“是”之后拆分一些句子,在“从不”之后拆分一些句子。我可以根据其中任何一个条件拆分句子,但不能同时根据这两个条件拆分句子。

str <- matrix(c("This is line one", "This is not line one", 
                "This can never be line one"), nrow = 3, ncol = 1)

>str
     [,1]                        
[1,] "This is line one"          
[2,] "This is not line one"      
[3,] "This can never be line one"

str2 <- apply(str, 1, function (x) strsplit(x, " is", fixed = TRUE))

> str2
[[1]]
[[1]][[1]]
[1] "This"      " line one"


[[2]]
[[2]][[1]]
[1] "This"          " not line one"


[[3]]
[[3]][[1]]
[1] "This can never be line one"

我想在“从不”之后拆分最后一句。我不知道该怎么做。

【问题讨论】:

  • 仅供参考 strsplit 已矢量化。不需要apply
  • 马贝strsplit(x," is | never ")?
  • @akrun 我说的是 Possible 重复,基本上这两个问题都想在正则表达式中使用 OR 运算符。此外,最好将相关帖子链接起来。
  • @akrun 帖子甚至没有用正则表达式标记,“is”和“never”是固定词。我们显然有不同的门槛来接受一个帖子作为欺骗,让我们保持不变。
  • 对不起,欺骗的链接与此无关。所以,重新打开它。

标签: r


【解决方案1】:

我们可以使用正则表达式环视在“是”或“从不”之后的空格处分割行。在这里,(?&lt;=\\bis)\\s+ 匹配 is| 后面的一个或多个空格 (\\s+) 以匹配“从不”字后面的空格 (\\s+)。

strsplit(str[,1], "(?<=\\bis)\\s+|(?<=\\bnever)\\s+", perl = TRUE)
#[[1]]
#[1] "This is"  "line one"

#[[2]]
#[1] "This is"      "not line one"

#[[3]]
#[1] "This can never" "be line one"   

如果我们还想删除 'is' 和 'never'

strsplit(str[,1], "(?:\\s+(is|never)\\s+)")
#[[1]]
#[1] "This"     "line one"

#[[2]]
#[1] "This"         "not line one"

#[[3]]
#[1] "This can"    "be line one"

【讨论】:

  • 您能否添加更多关于您的答案的详细信息?所有 \\
  • @ali 为第一个案例添加了一些细节。
  • 谢谢。我已经是第三个了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 2019-09-13
  • 2016-09-15
  • 2018-05-26
  • 1970-01-01
相关资源
最近更新 更多