使用标头字段作为每行的属性解析CSV文件 [英] Parse CSV file with header fields as attributes for each row

查看:128
本文介绍了使用标头字段作为每行的属性解析CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个CSV文件,以便将每一行视为一个对象,标题行是对象中属性的名称。

I would like to parse a CSV file so that each row is treated like an object with the header-row being the names of the attributes in the object. I could write this, but I'm sure its already out there.

这是我的CSV输入:

"foo","bar","baz"
1,2,3
"blah",7,"blam"
4,5,6

代码看起来像这样:

CSV.open('my_file.csv','r') do |csv_obj|
  puts csv_obj.foo   #prints 1 the 1st time, "blah" 2nd time, etc
  puts csv.bar       #prints 2 the first time, 7 the 2nd time, etc
end

对于Ruby的CSV模块,我相信我只能通过索引访问字段。我认为上面的代码将更有点可读性。任何想法?

With Ruby's CSV module I believe I can only access the fields by index. I think the above code would be a bit more readable. Any ideas?

推荐答案

使用Ruby 1.9及以上版本,可以得到一个可索引对象:

Using Ruby 1.9 and above, you can get a an indexable object:

CSV.foreach('my_file.csv', :headers => true) do |row|
  puts row['foo'] # prints 1 the 1st time, "blah" 2nd time, etc
  puts row['bar'] # prints 2 the first time, 7 the 2nd time, etc
end

这不是点语法,但它比数字索引更好。

It's not dot syntax but it is much nicer to work with than numeric indexes.

另外,对于Ruby 1.8.x FasterCSV 是你需要使用上面的语法。

As an aside, for Ruby 1.8.x FasterCSV is what you need to use the above syntax.

这篇关于使用标头字段作为每行的属性解析CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆