我有一个包含内容的CSV文件:
John,1,2,4,67,100,41,234
Maria,45,23,67,68,300,250
我需要阅读这些内容并将这些数据分成两部分:
1.a Legend1 = John
1.b Legend2 = Maria
2.a Data_array1 = [1,2,4,67,100,41,234]
2.b Data_array2 = [45,23,67,a,67,300,250]
这是我的代码;它读取内容并将内容与','
分开。
testsample = CSV.read('samples/linechart.csv')
CSV.foreach('samples/linechart.csv') do |row|
puts row
end
它的输出结果是一类数组元素。我被困在继续追求它。
答案 0 :(得分:0)
我建议不要使用CSV.read,因为它太简单了 - 相反,请使用File.open并读取每一行并将其视为一个大字符串。
例如:
# this turns the file into an array of lines
# eg you now have: ["John,1,2,4,67,100,41,234", "Maria,45,23,67,a,67,300,250"]
lines = File.readlines('samples/linechart.csv')
# if you want to do this for each line, just iterate over this array:
lines.each do |line|
# now split each line by the commas to turn it into an array of strings
# eg you have: ["john","1","2","4","67","100","41","234"]
values = line.split(',')
# now, grab the first one as you name and the rest of them as an array of strings
legend = values[0] # "john"
data_array = values[1..-1] # ["1","2","4","67","100","41","234"]
# now do what you need to do with the name/numbers eg
puts "#{legend}: [#{data_array.join(',')}]"
# if you want the second array to be actual numbers instead of strings, you can convert them to numbers using to_i (or to_f if you want floats instead of integers)
# the following says "take each value and call to_i on it and return the set of new values"
data_array = data_array.map(&:to_i)
end # end of iterating over the array
答案 1 :(得分:0)
首先从csv中获取数据,如:
require 'csv'
csv_text = File.read('/tmp/a.csv')
csv = CSV.parse(csv_text)
# => [["John", "1", "2", "4", "67", "100", "41", "234"], ["Maria", "45", "23", "67", "a", "67", "300", "250"]]
现在您可以根据您的要求格式化输出。例如:
csv.each.with_index(1){ |a, i|
puts "Legend#{i.to_s} = #{a[0]}"
}
# Legend1 = John
# Legend2 = Maria
答案 2 :(得分:0)
您可以寻找这个,
csv = CSV.new(body)
csv.to_a
您可以查看http://technicalpickles.com/posts/parsing-csv-with-ruby/
如果需要,也可以参考this。
答案 3 :(得分:0)
过度设计的版本;)
class Lines
class Line
attr_reader :legend, :array
def initialize(line)
@line = line
parse
end
private
def parse
@legend, *array = @line.strip.split(",")
@array = array.map(&:to_i)
end
end
def self.parse(file_name)
File.readlines(file_name).map do |line|
Line.new(line)
end
end
end
Lines.parse("file_name.csv").each do |o|
p o.legend
p o.array
puts
end
# Result:
#
# "John"
# [1, 2, 4, 67, 100, 41, 234]
#
# "Maria"
# [45, 23, 67, 68, 300, 250]
备注强>:
Lines.parse("file_name.csv")
会为您提供一系列响应方法的对象:legend
和array
;它分别包含名称和数字数组。