Show surrounding words when searching for a specific word in a text file (Ruby)
I am very new to ruby. I am trying to find any instance of a word in a text file (no problem). Then, when the word is found, it will show the surrounding text (maybe 3-4 words before and after the target word, rather than the whole line), output to the list of instances, and continue searching.
Example:
The swift brown fox jumped over the lazy dog.
Search word: jumped
Exit: ... a brown fox jumped over ...
Any help is appreciated.
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
a source to share
2 answers
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..."
This is not a perfect solution, just a way to go, so get around it.
+4
a source to share
Rails has a text helper called excerpt that does exactly that, so if you're trying to do it in a Rails view:
excerpt('The quick brown fox jumped over the lazy dog',
'jumped', :radius => 10)
=> "...brown fox jumped over the..."
If you want to use this external Rails (but you have Rails Rems installed) you can load 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..."
+3
a source to share