【问题标题】:In Ruby I need to split a sentence into sub-sentences在Ruby中,我需要将一个句子分成子句
【发布时间】:2015-09-30 10:23:04
【问题描述】:

给定字符串:

"See Spot Run"

我需要返回一个数组:

[ "See", "Spot", "run", "See Spot", "Spot run", "See Spot Run" ]

到目前为止,我有:

term = "The cat sat on the mat"
#=> "The cat sat on the mat" 

arr = term.split(" ")
#=> ["The", "cat", "sat", "on", "the", "mat"] 

arr.length.times.map { |i| (arr.length - i).times.map { |j| arr[j..j+i].join(" ") } }.flatten(1)
#=> ["The", "cat", "sat", "on", "the", "mat", "The cat", "cat sat", "sat on", "on the", "the mat", "The cat sat", "cat sat on", "sat on the", "on the mat", "The cat sat on", "cat sat on the", "sat on the mat", "The cat sat on the", "cat sat on the mat", "The cat sat on the mat"] 

这种情况会发生很多次,所以你能想出一种方法让它更有效率吗?

【问题讨论】:

    标签: arrays ruby string


    【解决方案1】:

    我会在循环中使用each_cons:(虽然它并没有更快)

    arr = %w[The cat sat on the mat]
    (1..arr.size).flat_map { |i| arr.each_cons(i).map { |words| words.join(' ') } }
    #=> ["The", "cat", "sat", "on", "the", "mat",
    #    "The cat", "cat sat", "sat on", "on the", "the mat",
    #    "The cat sat", "cat sat on", "sat on the", "on the mat",
    #    "The cat sat on", "cat sat on the", "sat on the mat",
    #    "The cat sat on the", "cat sat on the mat",
    #    "The cat sat on the mat"]
    

    【讨论】:

    • each_cons!伙计,我必须查看该文档页面大约五次试图找到该方法,但我完全错过了它。你是某种英雄!
    • 不幸的是,基准测试显示没有速度增加。奇怪,因为该方法是用 C 实现的。不过,至少我使用的是正确的 Ruby 方法。
    【解决方案2】:

    这是另一种方法,可能不如其他答案优雅。

    str = "The cat sat on the mat"
    words = str.split
    puts words.flat_map.with_index { |i, idx| 
        words.
            repeated_combination(idx + 1).
            select{ |*x| str[x.join(' ')]}.
            collect {|x| x.join(' ') }
    }
    

    输出

    The
    cat
    sat
    on
    the
    mat
    The cat
    cat sat
    sat on
    on the
    the mat
    The cat sat
    cat sat on
    sat on the
    on the mat
    The cat sat on
    cat sat on the
    sat on the mat
    The cat sat on the
    cat sat on the mat
    The cat sat on the mat
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多