【问题标题】:Split column by last word in sentence按句子中的最后一个单词拆分列
【发布时间】:2013-03-10 11:43:47
【问题描述】:

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

【问题讨论】:

    标签: regex r text-segmentation


    【解决方案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"
    

    【讨论】:

    • 这似乎有效,但如果最后一个“单词”中包含 -,则说明它不存在。我正在更新我的示例。
    • 这就是我试图解释的内容:我不确定这些词到底是什么,所以我使用了\\w\\d。你最好用\\S替换那部分:任何不是空格的字符。
    • \\S 替换\\W\\d 对我不起作用。除了带连字符的结束词外,此功能均有效。
    【解决方案2】:

    这看起来像是一项展望未来的工作。我们会在非空格的后面找到空格。

    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"
    

    【讨论】:

      【解决方案3】:

      这里使用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"
      

      【讨论】:

        【解决方案4】:

        这可能不完全适合你,但如果有人想知道如何在 python 中做到这一点

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

        请注意,col1 将打印为一个列表,您可以将其制成如下字符串:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-04
          • 2011-09-10
          • 1970-01-01
          • 1970-01-01
          • 2019-01-11
          • 1970-01-01
          相关资源
          最近更新 更多