0

タブ区切りのファイルがあり、選択した列をキーと値のペアに連結する必要があります。最初の3つの列は同じままですが、その後は任意の数の列を期待できます。3番目以降のすべての列は、キーと値のペアに連結する必要があります。

これが私のデータセットです:

col1 col2 col3 col4 col5

1 2 3 4 5

結果

col1 col2 col3 col4 | col5

1 2 3 col4 => 4 | col5 => 5

4

1 に答える 1

1

次の入力ファイルがある場合:

col1,col2,col3,col4,col5
1,2,3,this,that
2,3,4,some,more
3,4,5,a,b

次に、ヘッダーをプルして、各行を分割および破棄するには、次のようにします。

header, *lines = File.readlines('var.txt')
header = header.split(',')
header[-1].chomp!
rest_fields = header.slice(3..-1)
recs = lines.map do |line|
  line.chomp!
  f1, f2, f3, *rest = line.split(',')
  pairs = {}
  rest_fields.each do |f|
    pairs[f] = rest.shift
  end
  [f1, f2, f3, pairs]
end


recs.each do |rec|
  puts rec.inspect
end

それを実行すると:

["1", "2", "3", {"col4"=>"this", "col5"=>"that"}]
["2", "3", "4", {"col4"=>"some", "col5"=>"more"}]
["3", "4", "5", {"col4"=>"a", "col5"=>"b"}]

これはあなたが求めているものですか?

于 2012-11-20T00:54:02.030 に答える