按句子中的最后一个单词拆分列

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个回答

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"

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"

1
假设“单词”是字母数字混合的(在这种情况下,最后一个单词是一个或多个字母 \\w 或数字 \\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"

这似乎是有效的,但如果最后一个“单词”中有一个“-”,它就无法处理。我正在更新我的示例。 - Brandon Bertelsen
这就是我在解释中试图表达的:我不确定这些单词中确切可能包含什么内容,所以我使用了 \\w\\d。你最好用 \\S 替换那部分:任何非空格字符。 - Marius
将“\W\d”替换为“\S”对我没有起作用。这个函数除了连字符结尾的单词外都可以正常工作。 - Brandon Bertelsen

0

这可能不完全适合你,但如果有人想知道如何在Python中实现这个

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

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

请注意,col1将被打印为列表,您可以像这样将其转换为字符串:
#col1:
print " ".join(line.split(" ")[:-1])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接