使用CSV类在Ruby中解析.csv文件 [英] Using CSV Class to parse a .csv file in Ruby

查看:119
本文介绍了使用CSV类在Ruby中解析.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ruby 1.9.3,我发现了CSV类,但我不能让它工作。基本上,我想要能够操作CSV的各种选项,然后将一个.csv文件拖入一个数组使用,最终将该数组推回一个新的文件。



这是我目前的状态:

  require'csv'
CSV_Definition = CSV.New (:header_converters =>:symbol)

CSV_Total = CSV.Read(File.Path(C:\Scripts\SQL_Log_0.csv))
:header_converters
的正确方法。

。目前我不能得到IRB工作来解析这些代码(我不知道如何 require'csv'在IRB),所以我没有任何特定错误信息。我的期望是创建一个数组(CSV_Total)有一个没有符号的头。下一步是将该数组放回一个新文件中。基本上它会清理CSV文件。

解决方案

Ruby曾经有自己内置的CSV库, =http://fastercsv.rubyforge.org/ =nofollow noreferrer> FasterCSV 版本1.9,点击链接获取文档。



所有你需要的是使用通过 require'csv'语句导入CSV类,无论你想要使用它,并相应地处理。使用foreach语句构建数组非常简单,例如:



people.csv

  Merry,Christmas 
Hal,Apenyo
Terri,Aki
Willy,Byte

process_people.rb

  require'csv'$ do b 
$ b people = []

CSV.foreach(File.path(people.csv))do | row |
#其中,row [i]对应于csv
中的基于零的值/列。<< [row [0] ++ row [1]]
end

puts people.to_s
=> [[Merry Christmas],[Hal Apenyo],[Terri Aki],[Willy Byte]]


I'm using Ruby 1.9.3 and I've discovered the CSV class, but I can't get it to work. Basically, I want to be able to manipulate the various options for the CSV, and then pull a .csv file into an array to work with, eventually pushing that array back out into a new file.

This is what I have currently:

require 'csv'
CSV_Definition = CSV.New(:header_converters => :symbol)

CSV_Total = CSV.Read(File.Path("C:\Scripts\SQL_Log_0.csv"))

However, I don't think this is the right way to change the :header_converters. Currently I can't get IRB working to parse these pieces of code (I'm not sure how to require 'csv' in IRB) so I don't have any particular error message. My expectations for this will be to create an array (CSV_Total) that has a header with no symbols in it. The next step is to put that array back into a new file. Basically it would scrub CSV files.

解决方案

Ruby used to have it's own built in CSV library which has been replaced with FasterCSV as of version 1.9, click on the link for documentation.

All that's required on your part is to use to import the CSV class via require 'csv' statement wherever you want to use it and process accordingly. It's pretty easy to build an array with the foreach statement, e.g.,:

people.csv

Merry,Christmas
Hal,Apenyo
Terri,Aki
Willy,Byte

process_people.rb

require 'csv'    

people = []

CSV.foreach(File.path("people.csv")) do |row|
    # Where row[i] corresponds to a zero-based value/column in the csv
    people << [row[0] + " " + row[1]]
end

puts people.to_s 
=> [["Merry Christmas"], ["Hal Apenyo"], ["Terri Aki"], ["Willy Byte"]]

这篇关于使用CSV类在Ruby中解析.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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