如何应用strsplit创建一个没有空白的列表" "分子

时间:2017-01-27 16:45:01

标签: r

问题:如何应用 strsplit 创建一个没有空白的列表" "字符串开头有空格的元素?

代码:

     text <- c(" Please help me with this problem")

     dat <- data.frame(text)
     doc.list <- strsplit(as.character(dat[, 1]), "[[:space:]]+")

输出: [1]&#34;&#34; &#34;请&#34; &#34;帮助&#34; &#34;我&#34; &#34;与&#34; &#34;这&#34; &#34;问题&#34;

我想要的是什么: [1]&#34;请&#34; &#34;帮助&#34; &#34;我&#34; &#34;与&#34; &#34;这&#34; &#34;问题&#34;

3 个答案:

答案 0 :(得分:1)

您可以在执行拆分之前修剪空白区域:

strsplit(trimws(as.character(dat[, 1])), "[[:space:]]+")
#[1] "Please"  "help"    "me"      "with"    "this"    "problem"

答案 1 :(得分:0)

 strsplit(as.character(dat[, 1]), "(?<=\\w)(\\s+)",perl=T)[[1]]
#[1] " Please" "help"    "me"      "with"    "this"    "problem"

答案 2 :(得分:0)

您可以使用scan()代替。它将自动剥离该空白区域。

scan(text=as.character(dat$text), what="", quiet=TRUE)
# [1] "Please"  "help"    "me"      "with"    "this"    "problem"