从文件中提取列

时间:2012-09-06 01:16:13

标签: ruby file-io

我是Ruby的新程序员。我试图从文件中取两列并进行一些操作。我想我可以为此目的使用正则表达式?这是我的档案:

 MMU June 2002

  Dy MxT   MnT   AvT   HDDay  AvDP 1HrP TPcpn WxType PDir AvSp Dir MxS SkyC MxR MnR AvSLP

   1  88    59    74          53.8       0.00 F       280  9.6 270  17  1.6  93 23 1004.5
   2  79    63    71          46.5       0.00         330  8.7 340  23  3.3  70 28 1004.5
   3  77    55    66          39.6       0.00         350  5.0 350   9  2.8  59 24 1016.8
   4  77    59    68          51.1       0.00         110  9.1 130  12  8.6  62 40 1021.1
   5  90    66    78          68.3       0.00 TFH     220  8.3 260  12  6.9  84 55 1014.4
   6  81    61    71          63.7       0.00 RFH     030  6.2 030  13  9.7  93 60 1012.7
   7  73    57    65          53.0       0.00 RF      050  9.5 050  17  5.3  90 48 1021.8
   8  75    54    65          50.0       0.00 FH      160  4.2 150  10  2.6  93 41 1026.3
   9  86    32*   59       6  61.5       0.00         240  7.6 220  12  6.0  78 46 1018.6

这就是我想要做的事情:

 result_arr = []
 File.open("filename") do |f|
    while (line = f.gets)
      ary = line.split
      day = ary[0]
      max = ary[1]
      min = ary[2]
      result = max.to_i - min.to_i
     result_arr << result unless result == 0
   end
   puts result_arr.min
 end
 ~    

基本上我想要打印第一列和min的结果(Mxt - Mnt) 我正在使用数组,但我试图使用2D可能不知道如何做到这一点

非常感谢。

3 个答案:

答案 0 :(得分:0)

以下内容如何:

File.open("file.txt") do |f|
  while (line = f.gets)
    ary = line.split
    do_whatever_you_want_to(ary)
  end
end

String#split会将你的行变成一个数组,在空格和制表符处打破。

答案 1 :(得分:0)

将评论读到第一个答案,我认为这就是你想要做的事情:

results = [] #array to store the difference between the "Mxt" and "Mnt" fields

File.open("/path/to/file").each do |line|
  # skip header rows (there seem to be multiple in the file)
  # you might need to adjust the regex that checks for the presence of a data row
  # here I'm assuming that data rows start with a digit
  if line =~ /^\d/
    arr = line.split
    # you can use the column indices to get to the data you want
    results << arr[1] - arr[2]  
  end
end

答案 2 :(得分:0)

一般来说,你想要“解压缩”固定宽度数据,如下所示:

'   1  88    59 '.unpack('A6A6A6')
相关问题