←
PDF 243 / 520 Exercises
→
English · PDF 243
Original PDF page 243
中文 · PDF 243

sentences %>% head(5) %>% str_split(" ", simplify = TRUE) #> [,1] [,2] [,3] [,4] [,5] [,6] [,7] #> [1,] "The" "birch" "canoe" "slid" "on" "the" "smooth" #> [2,] "Glue" "the" "sheet" "to" "the" "dark" "blue" #> [3,] "It's" "easy" "to" "tell" "the" "depth" "of" #> [4,] "These" "days" "a" "chicken" "leg" "is" "a" #> [5,] "Rice" "is" "often" "served" "in" "round" "bowls." #> [,8] [,9] #> [1,] "planks." "" #> [2,] "background." "" #> [3,] "a" "well." #> [4,] "rare" "dish." #> [5,] "" ""

你还可以请求最大分割数量:

fields <- c("Name: Hadley", "Country: NZ", "Age: 35") fields %>% str_split(": ", n = 2, simplify = TRUE) #> [,1] [,2] #> [1,] "Name" "Hadley" #> [2,] "Country" "NZ" #> [3,] "Age" "35"

除了按模式分割字符串,你还可以按字符、行、句子和单词边界(boundary())进行分割:

x <- "This is a sentence. This is another sentence." str_view_all(x, boundary("word"))

str_split(x, " ")[[1]] #> [1] "This" "is" "a" "sentence." "" #> [6] "This" #> [7] "is" "another" "sentence." str_split(x, boundary("word"))[[1]] #> [1] "This" "is" "a" "sentence" "This" #> [6] "is" #> [7] "another" "sentence"

练习

    1. 将像 "apples, pears, and bananas" 这样的字符串分割成单个组成部分。
    1. 为什么使用 boundary("word") 分割比使用 " " 更好?