如何从 Ruby 中的 CSV 标题行创建变量

Posted

技术标签:

【中文标题】如何从 Ruby 中的 CSV 标题行创建变量【英文标题】:How to create variables from CSV header row in Ruby 【发布时间】:2012-03-19 03:17:51 【问题描述】:

我已经完成了 similar in Bash 的操作,但不确定如何在 2-3 行简洁的 Ruby 中做到这一点,尽管它似乎可以通过正确的编码功夫很快完成。

我有一个“file.csv”,其标题行如下所示:

Ticker,"Price","Market Cap","Average Volume","Analyst Recom","Relative Strength Index (14)","Sector","Industry","Dividend Yield","Beta","52-Week Low","52-Week High","50-Day Low","50-Day High","Company","50-Day Simple Moving Average","Country","P/E","Forward P/E","PEG","P/S","P/B","P/Cash","P/Free Cash Flow","Payout Ratio","EPS (ttm)","EPS growth this year","EPS growth next year","EPS growth past 5 years","EPS growth next 5 years","Sales growth past 5 years","EPS growth quarter over quarter","Sales growth quarter over quarter","Shares Outstanding","Shares Float","Insider Ownership","Insider Transactions","Institutional Ownership","Institutional Transactions","Float Short","Short Ratio","Return on Assets","Return on Equity","Return on Investment","Current Ratio","Quick Ratio","LT Debt/Equity","Total Debt/Equity","Gross Margin","Operating Margin","Profit Margin","Performance (Week)","Performance (Month)","Performance (Quarter)","Performance (Half Year)","Performance (Year)","Performance (Year)","Average True Range","Volatility (Week)","Volatility (Month)","20-Day Simple Moving Average","200-Day Simple Moving Average","Change from Open","Gap","Relative Volume","Change","Volume","Earnings Date","No."

接下来是大约 7000 行,如下所示:

FCD,27.89,,0.94,,66.75,"Financial","Exchange Traded Fund",3.13%,,19.75%,-0.36%,6.37%,-0.36%,"Focus Morningstar Consumer Defensive ETF",2.28%,"USA",,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,0.36%,3.07%,9.93%,10.85%,,2.01%,0.12,0.04%,0.21%,1.26%,6.69%,0.00%,-0.04%,0.96,-0.04%,900,,2186
FCE-A,14.59,2496.64,960.33,2.50,54.76,"Financial","Property Management",,2.83,56.55%,-24.87%,36.61%,-7.77%,"Forest City Enterprises Inc.",11.49%,"USA",,69.48,,2.2
5,1.58,10.87,,,-0.02,410.77%,250.00%,-10.06%,8.00%,1.54%,-28.77%,-9.00%,171.12,136.94,0.26%,-8.25%,74.80%,-0.13%,4.62%,6.59,0.46%,-0.12%,0.54%,,,4.35,4.35,39.54%,
4.82%,4.60%,-4.01%,8.96%,25.45%,13.10%,-22.80%,23.43%,0.44,3.07%,2.98%,-0.89%,1.49%,-1.62%,0.00%,0.47,-1.62%,449874,12/8/2010 4:30:00 PM,2187

给定一个股票代码“FCD”,我正在尝试将来自标题字段的大约 30 个新变量批量分配给与“FCD”行匹配的值。

每个新变量都应以fv_ 为前缀,其余部分与字段名称一样减去所有标点符号、空格、引号等(对变量不友好的内容)。

所以对于“FCD”,我想给出我的脚本:

fv_Ticker="FCD"  
fv_Price=27.89  
fv_MarketCap=""  
fv_VolatilityMonth=0.21  # if get String not Float because of trailing % in "0.21%" that's okay, will deal with it later
etc.

我应该注意,由于horrible slowdown using native Ruby 1.9.x CSV objects,我退出了使用任何类型的CSV.readCSV.foreach,这需要几分钟才能阅读,因此在重复运行的实时应用程序中是不可接受的。

相反,我一直在使用 Ruby 管道来“awk”分配从文件中读取的单个变量立即,如下所示:

$stock="FCD"
$dividend_yield = IO.readlines("|awk -F, '$1==\"#$stock\" print $9' finviz.AllStocks.csv")[0].to_f
$beta = IO.readlines("|awk -F, '$1==\"#$stock\" print $10' AllStocks.csv")[0].to_f

但现在它变得太复杂了,不能一概而论。它需要处理任何具有未知字段的类 CSV 文件,直到它看到的第一行。

【问题讨论】:

为什么是变量?为什么不是"FCD"=>someObject 的哈希? 哈希也可以,如果不是更好的话,但它需要很快。 Previously 将 CSV 读入 Ruby 失败了。 用变量填充符号表的效率不能低于哈希。此外,对任何东西使用全局变量,尤其是这个,不是一个好主意。 我在 bash 解决方案中看到您使用的是 Google 财务。 Google Finance 能否以比 CSV 或 XML 更有效的格式提供输出?可能是二进制格式?亚美尔? JSON?所有这些都更加高效。 可能使用snippets.dzone.com/posts/show/3899 【参考方案1】:

这个单行版本比last 还要好。它更短、更简单,而且特别吸引人,它将所有标题标题调整为(几乎)可变的唯一名称,因此我不必担心以后解析大部分内容:

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

结果:

csv_data.size
=> 1

csv_data.to_a
=> [[:ticker, :price, :market_cap, :average_volume, :analyst_recom, :relative_strength_index_14, :sector, :industry, :dividend_yield, :beta, :"52week_low", :"52week_high", :"50day_low", :"50day_high", :company, :"50day_simple_moving_average", :country, :pe, :forward_pe, :peg, :ps, :pb, :pcash, :pfree_cash_flow, :payout_ratio, :eps_ttm, :eps_growth_this_year, :eps_growth_next_year, :eps_growth_past_5_years, :eps_growth_next_5_years, :sales_growth_past_5_years, :eps_growth_quarter_over_quarter, :sales_growth_quarter_over_quarter, :shares_outstanding, :shares_float, :insider_ownership, :insider_transactions, :institutional_ownership, :institutional_transactions, :float_short, :short_ratio, :return_on_assets, :return_on_equity, :return_on_investment, :current_ratio, :quick_ratio, :lt_debtequity, :total_debtequity, :gross_margin, :operating_margin, :profit_margin, :performance_week, :performance_month, :performance_quarter, :performance_half_year, :performance_year, :performance_year, :average_true_range, :volatility_week, :volatility_month, :"20day_simple_moving_average", :"200day_simple_moving_average", :change_from_open, :gap, :relative_volume, :change, :volume, :earnings_date, :no], ["ANAD", 2.57, 175.2, 442.65, 2.9, 38.21, "Technology", "Semiconductor - Integrated Circuits", nil, 2.3, "33.85%", "-52.84%", "27.23%", "-20.19%", "Anadigics, Inc.", "-2.63%", "USA", nil, nil, nil, 1.15, 1.05, 3.08, nil, nil, -0.73, "-4002.36%", "57.90%", "-7.14%", "15.67%", "-1.69%", "-564.96%", "-39.37%", 68.17, 66.25, "3.87%", "-7.51%", "47.64%", "-6.24%", "3.30%", 4.95, "-23.34%", "-26.70%", "-26.33%", 4.89, 3.9, 0.0, 0.0, "20.35%", "-32.79%", "-32.27%", "-5.17%", "-7.22%", "21.23%", "-6.20%", "-50.39%", "17.35%", 0.16, "5.14%", "5.51%", "-13.04%", "-3.71%", "-4.10%", "0.00%", 0.95, "-4.10%", 421200, "2/22/2012 7:00:00 AM", 280]]


$company = csv_data[:company][0]
=> "Anadigics, Inc."

csv_data[:volatility_month]
=> ["5.51%"]

【讨论】:

【参考方案2】:

认为我正在做某事。一种让 Ruby 只看到两行 CSV 输入的中间方法,因此原生处理应该很快:

puts IO.readlines(%`|sed -n "1p; /^#$stock,/p" AllStocks.csv`) # sed filters out the gazillion other lines that make Ruby slow

它有效。由于sed,Ruby 只看到一个简短的 CSV,一行用于标题,一行用于数据,它会在瞬间加载,并且我有我的哈希:(我之后的关联数组)

$stock = "ANAD"

csv_data = CSV.parse IO.read(%`|sed -n "1p; /^#$stock,/p" AllStocks.csv`)
headers = csv_data.shift.map |i| i.to_s 
string_data = csv_data.map |row| row.map |cell| cell.to_s  
tickers = array_of_hashes = string_data.map |row| Hash[*headers.zip(row).flatten] 

pp tickers[0]    
=> "Ticker"=>"ANAD", "Price"=>"2.57", "Market Cap"=>"175.20", "Average Volume"=>"442.65", "Analyst Recom"=>"2.90", "Relative Strength Index (14)"=>"38.21", "Sector"=>"Technology", "Industry"=>"Semiconductor - Integrated Circuits", "Dividend Yield"=>"", "Beta"=>"2.30", "52-Week Low"=>"33.85%", "52-Week High"=>"-52.84%", "50-Day Low"=>"27.23%", "50-Day High"=>"-20.19%", "Company"=>"Anadigics, Inc.", "50-Day Simple Moving Average"=>"-2.63%", "Country"=>"USA", "P/E"=>"", "Forward P/E"=>"", "PEG"=>"", "P/S"=>"1.15", "P/B"=>"1.05", "P/Cash"=>"3.08", "P/Free Cash Flow"=>"", "Payout Ratio"=>"", "EPS (ttm)"=>"-0.73", "EPS growth this year"=>"-4002.36%", "EPS growth next year"=>"57.90%", "EPS growth past 5 years"=>"-7.14%", "EPS growth next 5 years"=>"15.67%", "Sales growth past 5 years"=>"-1.69%", "EPS growth quarter over quarter"=>"-564.96%", "Sales growth quarter over quarter"=>"-39.37%", "Shares Outstanding"=>"68.17", "Shares Float"=>"66.25", "Insider Ownership"=>"3.87%", "Insider Transactions"=>"-7.51%", "Institutional Ownership"=>"47.64%", "Institutional Transactions"=>"-6.24%", "Float Short"=>"3.30%", "Short Ratio"=>"4.95", "Return on Assets"=>"-23.34%", "Return on Equity"=>"-26.70%", "Return on Investment"=>"-26.33%", "Current Ratio"=>"4.89", "Quick Ratio"=>"3.90", "LT Debt/Equity"=>"0.00", "Total Debt/Equity"=>"0.00", "Gross Margin"=>"20.35%", "Operating Margin"=>"-32.79%", "Profit Margin"=>"-32.27%", "Performance (Week)"=>"-5.17%", "Performance (Month)"=>"-7.22%", "Performance (Quarter)"=>"21.23%", "Performance (Half Year)"=>"-6.20%", "Performance (Year)"=>"17.35%", "Average True Range"=>"0.16", "Volatility (Week)"=>"5.14%", "Volatility (Month)"=>"5.51%", "20-Day Simple Moving Average"=>"-13.04%", "200-Day Simple Moving Average"=>"-3.71%", "Change from Open"=>"-4.10%", "Gap"=>"0.00%", "Relative Volume"=>"0.95", "Change"=>"-4.10%", "Volume"=>"421200", "Earnings Date"=>"2/22/2012 7:00:00 AM", "No."=>"280"


tickers[0]["Volatility (Month)"].to_f
=> 5.51

【讨论】:

以上是关于如何从 Ruby 中的 CSV 标题行创建变量的主要内容,如果未能解决你的问题,请参考以下文章

如何从哈希数组创建 ruby​​ 类的实例?

创建数组后,如何正确遍历 CSV 文件中的行数组?

如何使用 Scala 从 Spark 中的列表或数组创建行

如何使用ruby [duplicate]从CSV文件中获取第二行

Ruby CSV - 获取当前行/行号

如何将 CSV 文件中的数据插入 Hive?