Rails中的制表符分隔文件解析 [英] Tab delimited file parsing in Rails
本文介绍了Rails中的制表符分隔文件解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像这样的文件
ID Name Car
1 Mike Honda
2 Adam Jim
这些值是制表符分隔的,从这里我想在Ruby中解析它,进入我的数据库。
These values are tab delimited, and from this I want to parse it in Ruby and put it into my database.
我试过下面的
require 'csv'
CSV.foreach("public/files/example.tab", {:col_sep => "\t"}) do |row|
@stuff = row[0]
end
但 @stuff
只是返回整个对象,并且似乎没有使用我指定的列分隔符。
but @stuff
just returns the whole entire object, and doesn't seem to be using the column separator I specified.
没有考虑到第一行是一个头。
It also does not take into account that the first row is a header.
如何解析在Ruby中的制表符分隔文件,如何告诉它第一行是标题?
How can I parse a tab delimited file in Ruby and how do I tell it that the first row is a header?
推荐答案
我已经成功与FasterCSV和Ruby 1.8.7,我相信它现在的核心csv库1.9, this:
I have had success with FasterCSV and Ruby 1.8.7, I believe it's now the core csv library in 1.9, using this:
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
这篇关于Rails中的制表符分隔文件解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文