2013-03-21 22 views
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 

回答

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" 
+0

+1和速度複選標記(rep(10k)= 0.05 s) – 2013-03-21 05:16:41

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" 
+0

這似乎是工作,但如果最後一個「單詞」中有一個「-',它並沒有考慮到它。我正在更新我的示例。 – 2013-03-21 04:42:44

+0

這就是我想要解釋的:我不確定在詞語中究竟是什麼,所以我用'\\ w \\ d'。你最好用'\\ S'替換那個部分:任何不是空格的字符。 – Marius 2013-03-21 04:46:30

+0

用'\\ S'代替'\\ W \\ d'不適用於我。除了帶連字符的結束詞之外,這起作用。 – 2013-03-21 04:52:40

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" 
+0

+1功能齊全。 – 2013-03-21 05:17:10

0

這可能不是究竟是你的,但如果有人想知道如何在Python做到這一點:

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

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

注意COL1將得到打印的清單,你可以做成這樣的字符串:

#col1: 
print " ".join(line.split(" ")[:-1]) 
相關問題