我已經使用Ruby的CSV模塊做了一些工作,但在忽略多個標題行時遇到了一些問題。忽略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 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
輸出表明,我對f.gets
電話實際上並沒有忽略那些線了,我不明白爲什麼。下面是輸出的前幾行:
Field is Clark
Field is and
Field is others
Field is 2007,
Field is USGS,
我試圖尋找一個教程或例子顯示了更復雜的CSV文件的處理,但沒有多少運氣。如果有人能指出我回答這個問題的資源,我將不勝感激(並希望將此標記爲接受我的具體問題的解決方案 - 但兩者都將不勝感激)。
使用Ruby 2.1。
你從哪裏找到「drop」方法?我沒有在文檔中看到它。 – 2014-10-19 19:56:21
@mohawkjohn以這種方式打開的文件是一個IO對象,其中包含Enumerable模塊。 – steenslag 2014-10-19 21:52:37
@mohawkjohn是正確的:http://ruby-doc.org/stdlib-2.1.2/libdoc/csv/rdoc/CSV.html – khelll 2014-10-19 22:01:05