如何打开一个文件并搜索一个词? [英] How to open a file and search for a word?

查看:124
本文介绍了如何打开一个文件并搜索一个词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何打开一个文件并使用Ruby搜索其中的一个单词? 解决方案

所有提出的解决方案都有一段时间O(n)的复杂性。为了简单起见,我使用 String#include?来检查单词。这可以用正则表达式来完成,形式为 string =〜regex



阅读完整的文件并

$ p $ File.read(filename).include?(word)

如果您的文件非常大,这不是一个最佳的解决方案,因为您会将完整的文件读入内存,然后开始搜索。你的内存复杂度是O(n)

逐行读取文件并在每一行中搜索

  File.open(filename)do | f | 
f.any? do | line |
line.include?(word)
end
end

如果你的文件非常大,但是你知道你的行被一个常量所限制,那么你现在的内存复杂度就是O(1)。

file and search in it



  File.open(filename)do | f | 
tmp = f.read(1024)
next如果tmp.include是真($)
直到f.eof?
tmp = tmp [( - 1 * word.size)..- 1] + f.read(1024)
next如果tmp.include为真(单词)
结尾
next false
end

在这个变体中,我们从文件中读取等大小的块。所以无论文件的条件如何,我们的内存复杂度都是O(1)

How can I open a file and search for a word inside it using Ruby?

解决方案

All presented solution have a time complexity of O(n). For simplicity I use String#include? to check for the word. This could be done instead with a regular expression in the form string=~ regex.

Read the complete file and search in it.

File.read(filename).include?(word)

If your file is very large, this is not an optimal solution, as you would read the complete file into memory and start searching afterwards. Your memory complexity is O(n)

Read the file line by line and search in each line

File.open(filename) do |f|
  f.any? do |line|
    line.include?(word)
  end
end

If your file is very large, but you know your lines are upperbounded by a constant value, you now have a memory complexity of O(1).

Read chunks of the file and search in it

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

In this variant, we are reading equaly sized chunks from the file. So no matter what the conditions of the file are, our memory complexity is O(1)

这篇关于如何打开一个文件并搜索一个词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆