5

YARQ(又一个正则表达式问题)。

我将如何将以下内容分成两列,确保最后一列包含句子中的最后一个单词,而第一列包含其他所有内容。

x <- c("This is a test",
       "Testing 1,2,3 Hello",
       "Foo Bar",
       "Random 214274(%*(^(* Sample",
       "Some Hyphenated-Thing"
       )

这样我最终得到:

col1                         col2
this is a                    test
Testing 1,2,3                Hello
Foo                          Bar
Random 214274(%*(^(*         Sample
Some                         Hyphenated-Thing
4

4 回答 4

9

这看起来像是一项展望未来的工作。我们会发现空格后面跟着不是空格的东西。

split <- strsplit(x, " (?=[^ ]+$)", perl=TRUE)
matrix(unlist(split), ncol=2, byrow=TRUE)

     [,1]                   [,2]              
[1,] "This is a"            "test"            
[2,] "Testing 1,2,3"        "Hello"           
[3,] "Foo"                  "Bar"             
[4,] "Random 214274(%*(^(*" "Sample"          
[5,] "Some"                 "Hyphenated-Thing"
于 2013-03-21T04:54:32.890 回答
4

这是一个使用strsplit

do.call(rbind,
  lapply(
    strsplit(x," "),
    function(y)
      cbind(paste(head(y,length(y)-1),collapse=" "),tail(y,1))
    )
)

或使用的替代实现sapply

t(
  sapply(
    strsplit(x," "),
    function(y) cbind(paste(head(y,length(y)-1),collapse=" "),tail(y,1))
  )
)

导致:

     [,1]                   [,2]              
[1,] "This is a"            "test"            
[2,] "Testing 1,2,3"        "Hello"           
[3,] "Foo"                  "Bar"             
[4,] "Random 214274(%*(^(*" "Sample"          
[5,] "Some"                 "Hyphenated-Thing"
于 2013-03-21T04:54:41.467 回答
1

假设“单词”是字母数字(在这种情况下,最后一个单词是 one 或 letters\\w或 digital \\d,如果需要,您可以添加更多类):

col_one = gsub("(.*)(\\b[[\\w\\d]+)$", "\\1", x, perl=TRUE)
col_two = gsub("(.*)(\\b[[\\w\\d]+)$", "\\2", x, perl=TRUE)

输出:

> col_one
[1] "This is a "            "Testing 1,2,3 "        "Foo "                 
[4] "Random 214274(%*(^(* "
> col_two
[1] "test"   "Hello"  "Bar"    "Sample"
于 2013-03-21T04:38:01.780 回答
0

这可能不完全适合您,但如果有人想知道如何在 python 中执行此操作

#col1:
print line.split(" ")[:-1]

#col2:
print line.split(" ")[-1]

Note that col1 will get printed as a list, which you can make into a string like this:

#col1:
print " ".join(line.split(" ")[:-1])
于 2013-03-21T06:41:03.207 回答