RoR:FasterCSV 到哈希

发布于 2024-07-10 11:56:19 字数 371 浏览 7 评论 0原文

我真的很难掌握如何有效地使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不再见 2024-07-17 11:56:19

简单:

h = Hash.new(0)
FasterCSV.read("file.csv")[1..-1].each {|row| h[row[0]] += 1}

与 CSV.read 的工作方式相同。

Easy:

h = Hash.new(0)
FasterCSV.read("file.csv")[1..-1].each {|row| h[row[0]] += 1}

Works the same with CSV.read, as well.

初懵 2024-07-17 11:56:19

我面前没有代码,但我相信 row.to_hash 可以做到这一点(其中 rowFasterCSV::Row 顺便说一句,

row.headers 应该为您提供一个标题数组。 检查文档了解更多信息: http://fastercsv.rubyforge.org/classes/FasterCSV/行.html

I don't have the code in front of me, but I believe row.to_hash does that (where row is the FasterCSV::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

就是爱搞怪 2024-07-17 11:56:19

我会使用 foreach,并尊重 nils - 否则我会冒“未定义的 nil.+ 方法”错误的风险......

counter = {}
FasterCSV.foreach("path_to_your_csv_file", :headers => :first_row) do |row|
  key=row[0]
  counter[key] = counter[key].nil? ? 1 : counter[key] + 1
end

I'd use foreach, and treat nils with respect - or else I'd risk an "undefined nil.+ method" error...

counter = {}
FasterCSV.foreach("path_to_your_csv_file", :headers => :first_row) do |row|
  key=row[0]
  counter[key] = counter[key].nil? ? 1 : counter[key] + 1
end
倾`听者〃 2024-07-17 11:56:19

嗯,会:

File.open("file.csv").readlines[1..-1].inject({}) {|acc,line| word = line.split(/,/).first; acc[word] ||= 0; acc[word] += 1; acc}

做吗?

[1..-1] 因为我们不希望标题行带有列名

,所以对于每一行,获取第一个单词,如果累加器不存在则将 0 放入累加器中,递增它,返回

Hum, would :

File.open("file.csv").readlines[1..-1].inject({}) {|acc,line| word = line.split(/,/).first; acc[word] ||= 0; acc[word] += 1; acc}

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文