0

How can I parse a large csv file in the following format:

A,1,X:1,X:1,X:1,X:1...

I need to save Aand all the 1's. I want to save the 1's as comma separated:

A 1,1,1,1,1,1...

Example of data:

4217,23,4217:0.1304,11045842:0.0870,11027563:0.0435,15055960:0.0435,12556773:0.0435,10317812:0.0435,21268053:0.0435,14982717:0.0435,12560416:0.0435,21684075:0.0435,12177392:0.0435,878710:0.0435,21777845:0.0435,11045966:0.0435,17109375:0.0435,15701596:0.0435,10312162:0.0435,11045878:0.0435

What I expect:

4217 4217,11045842,11027563,15055960,12556773,10317812,21268053,14982717,12560416,21684075,12177392,878710,21777845,11045966,17109375,15701596,10312162,11045878

1
  • What have you tried? What does the example data supposed to look like after your filter? Commented Mar 5, 2013 at 19:36

1 Answer 1

2

Suppose you have your input as a string in a variable, say row,

#Filename: test.rb

row = "4217,23,4217:0.1304,11045842:0.0870,11027563:0.0435,15055960:0.0435,12556773:0.0435,10317812:0.0435,21268053:0.0435,14982717:0.0435,12560416:0.0435,21684075:0.0435,12177392:0.0435,878710:0.0435,21777845:0.0435,11045966:0.0435,17109375:0.0435,15701596:0.0435,10312162:0.0435,11045878:0.0435";

row=row.split(',').map do |x|
        if(x.index(':')!=nil)
            x[0..(x.index(':')-1)]
        else
            x
        end
    end

keyElement = row[0];
arrayElement = row[2..-1];

puts keyElement;
for i in 0..arrayElement.length-1
    print(arrayElement[i] + ", ");
end
puts arrayElement[-1];

Here keyElement would contain 'A' and arrayElement would contain the comma seperated values as an array.

For your sample data, it gives:

>>ruby test.rb
4217
4217, 11045842, 11027563, 15055960, 12556773, 10317812, 21268053, 14982717, 12560416, 21684075, 12177392, 878710, 21777845, 11045966, 17109375, 15701596, 10312162, 11045878, 11045878

I would however recommend a hash, assuming you need to associate the array with the value 'A':

#row is mapped as before

hashElement = Hash.new();
hashElement[row[0]] = row[2..-1];
Sign up to request clarification or add additional context in comments.

4 Comments

@Yogzzz: Answer edited as well. It works perfectly for your sample data. I hope it helps.
@Yogzzz: I've added the values of keyElement and arrayElement I obtained for the sample data as well.
Please see my updated question with what I hope to return back. Thank you.
@Yogzzz: You need the array of X's, not the array of 1's eh? Answer changed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.