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

标签 ruby search text

我是 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/

相关文章:

ruby - 为什么没有 block 参数的方法定义可以接受 block ?

ruby-on-rails - ActiveRecord 查找连接和关联?

python - 如何设置 Canvas 文本项的字体​​大小?

excel - 如何将文本日志文件导入 Excel 列

ruby-on-rails - Sidekiq Redis::CannotConnectError:在生产环境中连接到 127.0.0.1:6379 上的 Redis 时出错

php - 改进 Laravel 5.2 的搜索引擎查询

algorithm - 寻找搜索算法名称

javascript - 如何在 javascript 中检测给定一维数组中的峰值?

html - CSS 继承 - 为什么 'later' 声明被 'earlier' 声明覆盖?

ruby-on-rails - 从 10 基数除以 60 基数?