在Rails中使用制表符分隔文件解析

时间:2011-11-17 21:05:56

标签: ruby-on-rails-3 csv

我有一个看起来像这样的文件

ID Name  Car
1  Mike  Honda
2  Adam  Jim

这些值是制表符分隔的,从中我想在Ruby中解析它并将其放入我的数据库中。

我试过以下

require 'csv'

CSV.foreach("public/files/example.tab", {:col_sep => "\t"}) do |row|
  @stuff = row[0]
end

@stuff只返回整个对象,似乎没有使用我指定的列分隔符。

它也没有考虑第一行是标题。

如何在Ruby中解析制表符分隔文件,如何告诉它第一行是标题?

3 个答案:

答案 0 :(得分:4)

我在FasterCSV和Ruby 1.8.7上取得了成功,我相信它现在是1.9中的核心csv库,使用它:

table = FasterCSV.read(result_file.to_file.path, { :headers => true, :col_sep => "\t", :skip_blanks => true })
unless table.empty?
    header_arry = Array.new
    table.headers.each do |h|
      #your header logic, e.g.
      # if h.downcase.include? 'pos'
        # header_arry << 'position'
      # end
      # simplest case here
      header_arry << h.downcase
      #which produces an array of column names called header_arry
    end

    rows = table.to_a
    rows.delete_at(0)
    rows.each do |row|
      #convert to hash using the column names
      hash = Hash[header_arry.zip(row)]
      # do something with the row hash
    end
  end

答案 1 :(得分:2)

更新

查看Gem“smarter_csv”https://github.com/tilo/smarter_csv/;它有几个有趣的功能来从CSV数据创建哈希。

上一个答案

这是我如何做的(沿着将CSV.read或CSV.parse返回的“数组数组”转换为“哈希数组”的方式...这使数据看起来更像ActiveRecord数据,以后稍微更容易处理..

require 'csv'

def process(csv_array)  # makes arrays of hashes out of CSV's arrays of arrays
  result = []
  return result if csv_array.nil? || csv_array.empty?
  headerA = csv_array.shift             # remove first array with headers from array returned by CSV
  headerA.map!{|x| x.downcase.to_sym }  # make symbols out of the CSV headers
  csv_array.each do |row|               #    convert each data row into a hash, given the CSV headers
    result << Hash[ headerA.zip(row) ]  #    you could use HashWithIndifferentAccess here instead of Hash
  end
  return result
end

# reading in the CSV data is now just one line:

csv_data = process( CSV.read( filename , { :col_sep => "\t"}) )

 => [{:id=>"1", :name=>"Mike", :car=>"Honda"}, 
     {:id=>"2", :name=>"Adam", :car=>"Jim"}] 

您现在可以像这样处理数据:

csv_data.each do |hash|
  # ...
end

另见:

http://as.rubyonrails.org/classes/HashWithIndifferentAccess.html

http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html

答案 2 :(得分:-1)

我用简单的方法来解析csv数据。这里的分隔符是制表符,空格,逗号或分号。它返回字段数组。

row_data = File.new("your_file.csv").read

row_data = row_data.split(/[ ,;\s]/).reject(&:empty?)