如何在Ruby中解析CSV文件中的列并将其存储为数组? [英] How do I parse columns in a CSV File in Ruby and store it as an array?

查看:255
本文介绍了如何在Ruby中解析CSV文件中的列并将其存储为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下CSV档案:

Date,Av,Sec,128,440,1024,Mixed,,rule,sn,version

6/30/2010,3.40,343,352.0,1245.8,3471.1,650.7,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 342,-0.26%,-0.91%,1.51%,-0.97%
6/24/2010,3.40,342,352.9,1257.2,3419.5,657.1,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 341,0.23%,0.50%,-1.34%,0.67%
6/17/2010,3.40,341,352.1,1251.0,3466.1,652.7,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 340,7.77%,5.32%,9.04%,1.71%
6/14/2010,3.40,340,326.7,1187.8,3178.7,641.7,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 339,-0.88%,-0.34%,-0.95%,0.05%
6/11/2010,3.40,339,329.6,1191.9,3209.2,641.4,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 338,0.58%,0.51%,-1.83%,0.99%
6/11/2010,3.40,338,327.7,1185.8,3269.1,635.1,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 335,-0.40%,-0.44%,1.46%,-1.96%
6/11/2010,3.40,335,329.0,1191.0,3221.9,647.8,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 333,-6.83%,-4.70%,-7.04%,-0.32%
6/11/2010,3.40,333,353.1,1249.8,3465.8,649.9,Mbps,on,s-2.8.6-38,4.9.1-229,,vs. 332,2.53%,2.02%,1.71%,2.14%

推荐答案

您需要随Ruby提供的 Ruby CSV模块。示例:

You need the Ruby CSV module which ships with Ruby. Example:

require 'csv'
require 'pp'

file = File.open( 'bar.csv' )
CSV::Reader.create( file ).each do |row|
  pp row[4..7]
end

这篇关于如何在Ruby中解析CSV文件中的列并将其存储为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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