2010-04-19 132 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..." 
相關問題