通过id ruby​​合并行csv [英] merge rows csv by id ruby

查看:103
本文介绍了通过id ruby​​合并行csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.csv文件,为简单起见,它是两个字段:ID和注释. id的行是重复的,其中每个注释字段都从生成该表的任何表满足max char,并且必须有另一行.现在,我需要将关联注释合并在一起,从而使用Ruby为每个唯一ID创建一行.

I have a .csv file that, for simplicity, is two fields: ID and comments. The rows of id's are duplicated where each comment field had met max char from whatever table it was generated from and another row was necessary. I now need to merge associative comments together thus creating one row for each unique ID, using Ruby.

为了说明这一点,我正在Ruby中尝试做到这一点:

To illustrate, I'm trying in Ruby, to make this:

ID |评论
1 |片段1
1 |片段2
2 |片段1
3 |片段1
3 |片段2
3 |片段3

ID | COMMENT
1 | fragment 1
1 | fragment 2
2 | fragment 1
3 | fragment 1
3 | fragment 2
3 | fragment 3

对此:

ID |评论
1 |片段1片段2
2 |片段1
3 |片段1片段2片段3

ID | COMMENT
1 | fragment 1 fragment 2
2 | fragment 1
3 | fragment 1 fragment 2 fragment 3

我已经接近找到一种使用inject({})和hashmap进行此操作的方法,但仍在努力使所有数据正确合并.同时,似乎我的代码因具有多个散列和数组而变得过于复杂,以至于无法在选择性行上进行合并.

I've come close to finding a way to do this using inject({}) and hashmap, but still working on getting all data merged correctly. Meanwhile seems my code is getting too complicated with multiple hashes and arrays just to do a merge on selective rows.

实现这种类型的行合并的最佳/最简单方法是什么?可以只用数组来完成吗?

What's the best/simplest way to achieve this type of row merge? Could it be done with just arrays?

希望您能提供有关在Ruby中通常如何执行此操作的建议.

Would appreciate advice on how one would normally do this in Ruby.

推荐答案

保留标题并使用ID分组:

Keep the headers and use group by ID:

rows = CSV.read 'comment.csv', :headers => true
rows.group_by{|row| row['ID']}.values.each do |group|
  puts [group.first['ID'], group.map{|r| r['COMMENT']} * ' '] * ' | '
end

您可以使用0和1,但我认为使用标头字段名称会更清楚.

You can use 0 and 1 but I think it's clearer to use the header field names.

这篇关于通过id ruby​​合并行csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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