如何打开文件并搜索单词?
如何使用Ruby打开文件并在其中搜索单词?
所有呈现的解决方案具有O(n)的时间复杂度。 为简单起见,我使用String#include?
检查这个词。 这可以用string=~ regex
forms的正则表达式来代替。
阅读完整的文件并在其中搜索。
File.read(filename).include?(word)
如果您的文件非常大,这不是最佳解决方案,因为您将完整的文件读入内存并在之后开始搜索。 你的记忆复杂度是O(n)
逐行读取文件并在每行中搜索
File.open(filename) do |f| f.any? do |line| line.include?(word) end end
如果你的文件非常大,但是你知道你的行是一个常量值的上限,你现在的内存复杂度为O(1)。
读取文件的块并在其中搜索
File.open(filename) do |f| tmp= f.read(1024) next true if tmp.include?(word) until f.eof? tmp= tmp[(-1*word.size)..-1] + f.read(1024) next true if tmp.include?(word) end next false end
在此变体中,我们从文件中读取等大小的块。 所以无论文件的条件是什么,我们的内存复杂度都是O(1)
这样的事情可能会有所帮助:
def word_exists_in_file f = File.open("your_file.txt") #opens the file for reading f.each do line print line if line.match /your_word_to_match/ return true end end false end
File.readlines(file).each {|l| l.grep(/#{exp_search}/).each {|r| puts file + ' : ' + r}}
尝试使用gem’search_in_file’,它可以帮助您按路径搜索指定文件或许多文件中的短语