加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 从没有重复的大文件中选择一个随机行

发布时间:2020-12-17 02:38:25 所属栏目:百科 来源:网络整理
导读:我正在尝试从一个大文件中选择一个随机行(百万行),而不是选择任何重复项.如果有一个骗局,那么我想继续挑选,直到找到一个非欺骗. 到目前为止我得到了什么: @already_picked = []def random_line chosen_line = nil chosen_line_number = nil File.foreach("O
我正在尝试从一个大文件中选择一个随机行(>百万行),而不是选择任何重复项.如果有一个骗局,那么我想继续挑选,直到找到一个非欺骗.

到目前为止我得到了什么:

@already_picked = []

def random_line
  chosen_line = nil
  chosen_line_number = nil
  File.foreach("OSPD4.txt").each_with_index do |line,number| 
    if rand < 1.0/(number+1)
      chosen_line_number = number
      chosen_line = line
    end
  end
  chosen_line
  if @already_picked.include(chosen_line_number)?
    # what here?
  else
    @already_picked << chosen_line_number
  end
end

100.times do |t|
  random_line
end

我不知道在if子句中该怎么做

解决方法

100万行不是很多.如果它们平均100字节/行,则内存为100MB.这么简单,继续前进

File.readlines("file").sample(100)

如果你开始说话大于容易适合内存,那么下一步是对文件进行一次传递以记录行位置,然后从中提取样本.

class RandomLine
  def initialize(fn)
    @file = File.open(fn,'r')
    @positions = @file.lines.inject([0]) { |m,l| m << m.last + l.size }.shuffle
  end

  def pick
    @file.seek(@positions.pop)
    @file.gets
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读