【问题标题】:How do I read a text file into an array of array (each sub-array being a row in the text file?)如何将文本文件读入数组数组(每个子数组都是文本文件中的一行?)
【发布时间】:2013-07-26 20:57:57
【问题描述】:

所以我在 Ruby 方面几乎是一个 n00b,并且我已经整理了一个代码来解决 MinCut 问题(对于作业,是的 - 我整理并测试的那部分代码),我无法弄清楚如何读取文件并将其放入数组数组中。我有一个文本文件要读取,列的长度不同,如下所示

1 37 79 164

2 123 134

3 48 123 134 109

我想将它读入一个二维数组,其中每一行和每一列都被分割,每一行进入一个数组。所以上面例子的结果数组是:

[[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]

我读取文本文件的代码如下:

def read_array(file, count)
  int_array = []
  File.foreach(file) do |f|
    counter = 0
    while (l = f.gets and counter < count ) do
      temp_array = []
      temp_array << l.to_i.split(" ")
      int_array << temp_array
      counter = counter + 1
    end

  end
  return int_array
end

非常感谢任何帮助!

另外,如果有帮助,我目前遇到的错误是“block in read_array': private method 'gets' called for #”

我尝试了一些方法,但收到了不同的错误消息...

【问题讨论】:

    标签: ruby arrays file split


    【解决方案1】:
    File.readlines('test.txt').map do |line|
      line.split.map(&:to_i)
    end
    

    说明

    readlines 读取整个文件并用换行符分割它。它看起来像这样:

    ["1 37 79 164\n", "2 123 134\n", "3 48 123 134 109"]
    

    现在我们遍历行(使用map)并将每行拆分为其数字部分(split

    [["1", "37", "79", "164"], ["2", "123", "134"], ["3", "48", "123", "134", "109"]]
    

    这些项目仍然是字符串,因此内部的map 将它们转换为整数(to_i)。

    [[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]]
    

    【讨论】:

    【解决方案2】:

    Ruby 只用了几行代码就可以帮你搞定:

    tmp.txt

    1 2 3
    10 20 30 45
    4 2
    

    Ruby 代码

    a = []
    File.open('tmp.txt') do |f|
      f.lines.each do |line|
        a << line.split.map(&:to_i)
      end
    end
    
    puts a.inspect
    # => [[1, 2, 3], [10, 20, 30, 45], [4, 2]]
    

    【讨论】:

    • 非常感谢!这就是我喜欢 ruby​​ 的原因,每次我遇到问题时,答案都会比以前想象的要容易得多
    【解决方案3】:

    发生代码中的错误是因为您在对象 f 上调用方法 gets,它是 String,而不是您所期望的 File(请查看 the documentation for IO#foreach 了解更多信息) .

    我建议你改写成更简单、更 Ruby 风格的代码,而不是修复你的代码,我会这样写:

    def read_array(file_path)
      File.foreach(file_path).with_object([]) do |line, result|
        result << line.split.map(&:to_i)
      end
    end
    

    鉴于此file.txt

    1 37 79 164
    2 123 134
    3 48 123 134 109
    

    它产生这个输出:

    read_array('file.txt')
    # => [[1, 37, 79, 164], [2, 123, 134], [3, 48, 123, 134, 109]] 
    

    【讨论】:

    • +1 用于解释他遇到的错误。我们其他人都忘记了:)
    【解决方案4】:
    array_line = []  
    
    if File.exist? 'test.txt'
      File.foreach( 'test.txt' ) do |line|
          array_line.push line
      end
    end
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
    【解决方案5】:
    def read_array(file)
      int_array = []
    
      File.open(file, "r").each_line { |line| int_array << line.split(' ').map {|c| c.to_i} }
    
      int_array
    end
    

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 2019-08-31
      • 2015-08-18
      • 1970-01-01
      • 2017-07-16
      • 2022-08-08
      • 2020-05-18
      • 1970-01-01
      相关资源
      最近更新 更多