在文本文件中搜索特定单词时显示周围的单词(Ruby)

时间:2010-04-19 17:40:45

标签: ruby search text

我对红宝石很新。我正在尝试在文本文件中搜索任何单词的实例(不是问题)。然后,当发现该单词时,它将显示周围的文本(可能是目标单词之前和之后的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

2 个答案:

答案 0 :(得分:4)

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..."

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

答案 1 :(得分:3)

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..."
相关问题