从CSV导入到Ruby数组,将第1个字段作为散列键,然后查找给定标题行的字段值 [英] import from CSV into Ruby array, with 1st field as hash key, then lookup a field's value given header row

查看:268
本文介绍了从CSV导入到Ruby数组,将第1个字段作为散列键,然后查找给定标题行的字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许有人可以帮助我。

Maybe somebody can help me.

从以下CSV文件开始:

Starting with a CSV file like so:

Ticker,"Price","Market Cap"
ZUMZ,30.00,933.90
XTEX,16.02,811.57
AAC,9.83,80.02

我设法将它们读入数组:

I manage to read them into an array:

require 'csv'
tickers = CSV.read("stocks.csv", {:headers => true, :return_headers => true, :header_converters => :symbol, :converters => :all} )

要验证数据,请按以下步骤操作:

To verify data, this works:

puts tickers[1][:ticker]
ZUMZ

但是这不会:

puts tickers[:ticker => "XTEX"][:price]

我如何使用ticker字段作为唯一键,这样我可以容易地查找任何其他字段关联地定义在输入的第1行?处理更多列和行。

How would I go about turning this array into a hash using the ticker field as unique key, such that I could easily look up any other field associatively as defined in line 1 of the input? Dealing with many more columns and rows.

非常感谢!

推荐答案

为了获得最好的两个世界(从一个巨大的文件非常快的阅读和本地Ruby CSV对象的好处)我的代码已经演变成这个方法:

To get the best of both worlds (very fast reading from a huge file AND the benefits of a native Ruby CSV object) my code had since evolved into this method:

$stock="XTEX"
csv_data = CSV.parse IO.read(%`|sed -n "1p; /^#{$stock},/p" stocks.csv`), {:headers => true, :return_headers => false, :header_converters => :symbol, :converters => :all}

# Now the 1-row CSV object is ready for use, eg:
$company = csv_data[:company][0]
$volatility_month = csv_data[:volatility_month][0].to_f
$sector = csv_data[:sector][0]
$industry = csv_data[:industry][0]
$rsi14d = csv_data[:relative_strength_index_14][0].to_f

这更接近我的原始方法, 1的包含头的输入csv文件。内联 sed 指令负责这一点 - 而且整个事情都是即时的。这比最后一个好,因为现在我可以从Ruby访问所有字段,并且关联地,不再关心列号如 awk 的情况。

which is closer to my original method, but only reads in one record plus line 1 of the input csv file containing the headers. The inline sed instructions take care of that--and the whole thing is noticably instant. This this is better than last because now I can access all the fields from Ruby, and associatively, not caring about column numbers anymore as was the case with awk.

这篇关于从CSV导入到Ruby数组,将第1个字段作为散列键,然后查找给定标题行的字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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