我是 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
最佳答案
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..."
这不是完美的解决方案,只是路径,因此请绕过它。
关于ruby - 在文本文件中搜索特定单词时显示周围的单词 (Ruby),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669580/