RoR:FasterCSV 到哈希
我真的很难掌握如何有效地使用 FasterCSV 来完成我想要的事情。
我有一个 CSV 文件; 说:
ID,day,site
test,tuesday,cnn.com
bozo,friday,fark.com
god,monday,xkcd.com
test,saturday,whatever.com
我要遍历这个文件并最终得到一个哈希值,该哈希值具有第一列出现次数的计数器。 所以:
["test" => 2, "bozo" => 1, "god" => 1]
我需要能够在不事先了解第一列中的值的情况下执行此操作。
?
I'm really struggling with grasping how to effectively use FasterCSV to accomplish what I want.
I have a CSV file; say:
ID,day,site
test,tuesday,cnn.com
bozo,friday,fark.com
god,monday,xkcd.com
test,saturday,whatever.com
I what to go through this file and end up with a hash that has a counter for how many times the first column occurred. So:
["test" => 2, "bozo" => 1, "god" => 1]
I need to be able to do this without prior knowledge of the values in the first column.
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单:
与 CSV.read 的工作方式相同。
Easy:
Works the same with CSV.read, as well.
我面前没有代码,但我相信
row.to_hash
可以做到这一点(其中row
是FasterCSV::Row
顺便说一句,row.headers
应该为您提供一个标题数组。 检查文档了解更多信息: http://fastercsv.rubyforge.org/classes/FasterCSV/行.htmlI don't have the code in front of me, but I believe
row.to_hash
does that (whererow
is theFasterCSV::Row
of the current record)row.headers
should give you an array of the headers, incidentally. Check the docs for more: http://fastercsv.rubyforge.org/classes/FasterCSV/Row.html我会使用 foreach,并尊重 nils - 否则我会冒“未定义的 nil.+ 方法”错误的风险......
I'd use foreach, and treat nils with respect - or else I'd risk an "undefined nil.+ method" error...
嗯,会:
做吗?
[1..-1] 因为我们不希望标题行带有列名
,所以对于每一行,获取第一个单词,如果累加器不存在则将 0 放入累加器中,递增它,返回
Hum, would :
do ?
[1..-1] because we don't want the header line with the column names
then, for each line, get the first word, put 0 in the accumulator if it does not exist, increment it, return