【问题标题】:Show surrounding words when searching for a specific word in a text file (Ruby)在文本文件中搜索特定单词时显示周围的单词 (Ruby)
【发布时间】:2011-02-09 19:21:06
【问题描述】:

我对红宝石很陌生。我正在尝试在文本文件中搜索单词的任何实例(不是问题)。然后当发现单词时,它会显示周围的文本(可能是目标单词前后的 3-4 个单词,而不是整行),输出到实例列表并继续搜索。

例子:

敏捷的棕狐跳过了懒惰的狗。

搜索词:跳跃

输出:...棕狐跳过...

感谢任何帮助。

def word_exists_in_file
   f = File.open("test.txt")
   f.each do line
      print line
      if line.match /someword/
         return true
      end
   end
   false
end

【问题讨论】:

    标签: ruby search text


    【解决方案1】:
    def find_word(string, word)
      r1 = /\w+\W/
      r2 = /\W\w+/
      "..." + string.scan(/(#{r1}{0,2}#{word}#{r2}{0,2})/i).join("...") + "..."
    end
    
    string = "The quick brown fox jumped over the lazy dog."
    
    find_word(string, "the")
    #=> "...The quick brown...jumped over the lazy dog..."
    
    find_word(string, "over")
    #=> "...fox jumped over the lazy..."
    

    这不是完美的解决方案,只是路径,所以要解决它。

    【讨论】:

      【解决方案2】:

      Rails 有一个名为 excerpt 的文本帮助器,它正是这样做的,所以如果你想在 Rails 视图中这样做:

      excerpt('The quick brown fox jumped over the lazy dog',
              'jumped', :radius => 10)
      => "...brown fox jumped over the..."
      

      如果你想在 Rails 之外使用它(但你已经安装了 Rails gems)你可以加载 ActionView:

      require "action_view"
      ActionView::Base.new.excerpt('The quick brown fox jumped over the lazy dog',
                                       'jumped', :radius => 10)
      
      => "...brown fox jumped over the..."
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多