递归拆分字符串



假设我有这样的文本:

pattern = "This_is some word/expression I'd like to parse:intelligently(using special symbols-like '.')"

挑战在于如何使用中的单词分隔符将其拆分为单词

c(" ","-","/","\","_",":","(",")",".",",")

家庭。

所需结果:

"This" "is" "some" "word" "expression" "I'd" "like" "to" "parse" "intelligently" "using" "special" "symbols" "like"

方法

我可以使用进行sapplyfor循环

 keywords = unlist(strsplit(pattern," "))
 keywords = unlist(strsplit(keywords,"-"))

#等

问题:

但是使用Reduce(f, x, init, accummulate=TRUE)的解决方案是什么?

此处不需要Reduce。你应该能够做以下事情:

splitters <- c(" ","/","\","_",":","(",")",".",",","-") # dash should come last
pattern <- paste0("[", paste(splitters, collapse = ""), "]")
string <- "This_is some word/expression I'd like to parse:intelligently(using special symbols-like '.')"
strsplit(string, pattern)[[1]]
#  [1] "This"          "is"            "some"          "word"         
#  [5] "expression"    "I'd"           "like"          "to"           
#  [9] "parse"         "intelligently" "using"         "special"      
# [13] "symbols"       "like"          "'"             "'"  

请注意,regex字符类中的-应该排在第一位或最后一位,因此我相应地编辑了您的"splitters"向量。此外,您可能希望在"模式"的末尾添加一个+,以防您想将多个空格折叠为一个空格。

您可以使用选项perl = TRUE,然后在标点符号或空格上进行拆分

> strsplit(pattern, '[[:punct:]]|[[:space:]]', perl = TRUE)
[[1]]
 [1] "This"          "is"            "some"          "word"          "expression"   
 [6] "I"             "d"             "like"          "to"            "parse"        
[11] "intelligently" "using"         "special"       "symbols"       "like"         
[16] ""    

我会选择(它将保持"I'd"在一起)

strsplit(pattern, "[^[:alnum:][:digit:]']")
## [[1]]
##  [1] "This"          "is"            "some"          "word"          "expression"    "I'd"           "like"          "to"            "parse"        
## [10] "intelligently" "using"         "special"       "symbols"       "like"          "'"             "'"   

相关内容

  • 没有找到相关文章

最新更新