Ruby 忽略CSV中的多个标题行
我曾经使用过Ruby的CSV模块,但是在让它忽略多个标题行时遇到了一些问题 具体来说,以下是我要解析的文件的前二十行:Ruby 忽略CSV中的多个标题行,ruby,csv,Ruby,Csv,我曾经使用过Ruby的CSV模块,但是在让它忽略多个标题行时遇到了一些问题 具体来说,以下是我要解析的文件的前二十行: USGS Digital Spectral Library splib06a Clark and others 2007, USGS, Data Series 231. For further information on spectrsocopy, see: http://speclab.cr.usgs.gov ASCII Spectral Data file conte
USGS Digital Spectral Library splib06a
Clark and others 2007, USGS, Data Series 231.
For further information on spectrsocopy, see: http://speclab.cr.usgs.gov
ASCII Spectral Data file contents:
line 15 title
line 16 history
line 17 to end: 3-columns of data:
wavelength reflectance standard deviation
(standard deviation of 0.000000 means not measured)
( -1.23e34 indicates a deleted number)
----------------------------------------------------
Olivine GDS70.a Fo89 165um W1R1Bb AREF
copy of splib05a r 5038
0.205100 -1.23e34 0.090781
0.213100 -1.23e34 0.018820
0.221100 -1.23e34 0.005416
0.229100 -1.23e34 0.002928
实际的标题在第十行给出,第十七行是实际数据的起点
这是我的密码:
require "nyaplot"
# Note that DataFrame basically just inherits from Ruby's CSV module.
class SpectraHelper < Nyaplot::DataFrame
class << self
def from_csv filename
df = super(filename, col_sep: ' ') do |csv|
csv.convert do |field, info|
STDERR.puts "Field is #{field}"
end
end
end
end
def csv_headers
[:wavelength, :reflectance, :standard_deviation]
end
end
def read_asc filename
f = File.open(filename, "r")
16.times do
line = f.gets
puts "Ignoring #{line}"
end
d = SpectraHelper.from_csv(f)
end
我试图寻找一个教程或例子,其中显示了更复杂的CSV文件的处理,但没有太多的运气。如果有人能为我指出一个能回答这个问题的资源,我将不胜感激,并且更愿意将其标记为已被接受,而不是我的具体问题的解决方案,但双方都将不胜感激
使用Ruby 2.1。它认为您使用的是::open,它使用IO.open。此方法将再次打开该文件 我稍微修改了一下脚本
require 'csv'
class SpectraHelper < CSV
def self.from_csv(filename)
df = open(filename, 'r' , col_sep: ' ') do |csv|
csv.drop(16).each {|c| p c}
end
end
end
def read_asc(filename)
SpectraHelper.from_csv(filename)
end
read_asc "data/csv1.csv"
我不会使用CSV模块,因为您的文件格式不好。以下代码将读取该文件并为您提供一个记录数组:
lines = File.open(filename,'r').readlines
lines.slice!(0,16)
records = lines.map {|line| line.chomp.split}
记录输出:
事实证明,这里的问题不在于我对CSV的理解,而在于Nyaplot::DataFrame处理CSV文件 基本上,Nyaplot实际上并不将事物存储为CSV。CSV只是一种中间格式。因此,一种处理文件的简单方法利用了@khelli的建议:
def read_asc filename
Nyaplot::DataFrame.new(CSV.open(filename, 'r',
col_sep: ' ',
headers: [:wavelength, :reflectance, :standard_deviation],
converters: :numeric).
drop(16).
map do |csv_row|
csv_row.to_h.delete_if { |k,v| k.nil? }
end)
end
谢谢大家的建议。您在哪里找到了滴水法?我在文档中没有看到它。@mohawkjohn以这种方式打开的文件是一个IO对象,其中包括可枚举模块。这实际上不是我所问问题的答案。
[["0.205100", "-1.23e34", "0.090781"], ["0.213100", "-1.23e34", "0.018820"], ["0.221100", "-1.23e34", "0.005416"], ["0.229100", "-1.23e34", "0.002928"]]
def read_asc filename
Nyaplot::DataFrame.new(CSV.open(filename, 'r',
col_sep: ' ',
headers: [:wavelength, :reflectance, :standard_deviation],
converters: :numeric).
drop(16).
map do |csv_row|
csv_row.to_h.delete_if { |k,v| k.nil? }
end)
end