Ruby如何合并两个具有略微不同标题的CSV文件 [英] Ruby how to merge two CSV files with slightly different headers

查看:154
本文介绍了Ruby如何合并两个具有略微不同标题的CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个CSV文件,其中包含一些常见的标题,而其他只显示在一个或另一个中的文件,例如:

I have two CSV files with some common headers and others that only appear in one or in the other, for example:

# csv_1.csv
H1,H2,H3
V11,V22,V33
V14,V25,V35



# csv_2.csv
H1,H4
V1a,V4b
V1c,V4d

我想合并两个文件,并获取一个新的CSV文件,其中包含以前CSV文件的所有信息。在需要时注入新列,并为新单元格提供 null 值。

I would like to merge both and obtain a new CSV file that combines all the information for the previous CSV files. Injecting new columns when needed, and feeding the new cells with null values.

结果示例:

H1,H2,H3,H4
V11,V22,V33,
V14,V25,V35,
V1a,,,V4b
V1c,,,V4d 


推荐答案

:)

require "csv"

module MergeCsv
  def self.run(csv_1_path, csv_2_path)
    csv_1 = CSV.read(csv_1_path, headers: true)
    csv_2 = CSV.read(csv_2_path, headers: true)
    puts merge(csv_1, csv_2)
  end

  def self.merge(csv_1, csv_2)
    headers = (csv_1.headers + csv_2.headers).uniq.sort

    hash_array = [csv_1, csv_2].flat_map &method(:csv_to_hash_array)

    CSV.generate do |merged_csv|
      merged_csv << headers

      hash_array.each do |row|
        merged_csv << row.values_at(*headers)
      end
    end
  end

  def self.csv_to_hash_array(csv)
    csv.to_a[1..-1].map do |row|
      Hash[csv.headers.zip(row)]
    end
  end
end

if(ARGV.length != 2)
  puts "Use: ruby merge_csv.rb <file_path_csv_1> <file_path_csv_2>"
  exit 1
end

puts MergeCsv.run(ARGV[0], ARGV[1])

这篇关于Ruby如何合并两个具有略微不同标题的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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