2010-04-19 60 views
2

我对Ruby非常陌生。我试图在文本文件中搜索任何单词的实例(而不是问题)。然后,当发现该单词时,它会显示周围的文本(可能是目标单词前后的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 

回答

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

这不是完美的解决方案,只是路径,那么解决它。

3

Rails有所谓的摘录文字帮手正是这样做的,所以如果你想做到这一点Rails视图内:

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

如果你想用这个外面的Rails(但你有安装Rails宝石)你可以加载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..." 
相关问题