我试图根据不同的标准来分割句子。我希望在“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"我想在“从不”之后把最后一句分开。我不知道该怎么做。
发布于 2016-09-05 06:28:14
我们可以使用regex旁观者在“is”或“to”之后的空间分割行。在这里,(?<=\\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"https://stackoverflow.com/questions/39324793
复制相似问题