这个问题在这里已经有了答案:
R strsplit with multiple unordered split arguments?
(4 个回答)
5年前关闭。
我试图根据不同的标准拆分句子。我希望在"is"之后拆分一些句子,在“从不”之后拆分一些句子。我能够根据这两个条件之一拆分句子,但不能同时拆分这两个条件。
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"
我想在“从不”之后拆分最后一句话。我不知道该怎么做。
最佳答案
我们可以使用正则表达式环视在“is”或“never”之后的空格处拆分行。在这里,(?<=\\bis)\\s+
匹配 \\s+
后面的一个或多个空格 ( is
)或 |
匹配“从不”单词后面的空格( \\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"和“从不”也
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"
关于具有多个条件的 R strsplit(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324793/