如何在ruby中比较两个文本文件的值

时间:2022-11-29 20:28:19

I have two text file, and they have one same field(pet). I want to combine two file and output a new file contain three fields(owner pet buyer). My code is mainly depends on if both file have the same pet(name and number of pets) than I will add the name of buyer to the field of buyer in the new file. It should print out only if the two file have same filed of pet.

我有两个文本文件,它们有一个相同的字段(pet)。我想结合两个文件并输出一个包含三个字段的新文件(所有者宠物买家)。我的代码主要取决于两个文件是否具有相同的宠物(宠物的名称和数量),而不是我将在新文件中将买方的名称添加到买方的字段中。只有当两个文件具有相同的宠物归档时才应打印出来。

But my code did not work as I want, need some help, thanks.

但是我的代码没有按照我的意愿运行,需要一些帮助,谢谢。

input_file_1 (.txt)

input_file_1(.txt)

owner pet
Michael dog, cat
John pig, rabbit
Marry dog, cat

input_file_2 (.txt)

input_file_2(.txt)

buyer pet
Sean cat, dog
Mark cat, dog
Joy dog, mouse
Tina cat, dog

I want the result to look like this:

我希望结果看起来像这样:

owner pet buyer
Michael cat, dog Sean, Mark, Tina
Mary cat, dog Sean, Mark, Tina

My code looks like this:

我的代码如下所示:

input_file_1 = ARGV[0]
input_file_2 = ARGV[1]

hash_1 = {}
File.readlines(input_file_1, "\n").each do |line|
  owner, pet = line.chomp.split("\t")
  hash_1[owner] = pet
end

hash_2 = {}
File.readlines(input_file_2, "\n").each do |line|
  buyer, pet = line.chomp.split("\t")
  hash_2[buyer] = pet
end

hash_1.each do |key, value|
  if hash_2.has_value? value
    puts "#{key}\t#{value}\t#{hash_2[key]}"
  end
end

1 个解决方案

#1


0  

I would suggest you use the pet as key:

我建议你用宠物作为关键:

input_file_1 = ARGV[0]
input_file_2 = ARGV[1]

hash_1 = Hash.new([])
File.readlines(input_file_1, "\n").each do |line|
  owner, pet = line.chomp.split("\t")
  hash_1[pet] += [owner]
end

hash_2 = Hash.new([])
File.readlines(input_file_2, "\n").each do |line|
  buyer, pet = line.chomp.split("\t")
  hash_2[pet] += [buyer]
end

hash_1.each do |pet, owners|
  if hash_2.include? pet
    owners.each do |owner|
      puts "#{owner}\t#{pet}\t#{hash_2[pet].join(", ")}"
    end
  end
end

#1


0  

I would suggest you use the pet as key:

我建议你用宠物作为关键:

input_file_1 = ARGV[0]
input_file_2 = ARGV[1]

hash_1 = Hash.new([])
File.readlines(input_file_1, "\n").each do |line|
  owner, pet = line.chomp.split("\t")
  hash_1[pet] += [owner]
end

hash_2 = Hash.new([])
File.readlines(input_file_2, "\n").each do |line|
  buyer, pet = line.chomp.split("\t")
  hash_2[pet] += [buyer]
end

hash_1.each do |pet, owners|
  if hash_2.include? pet
    owners.each do |owner|
      puts "#{owner}\t#{pet}\t#{hash_2[pet].join(", ")}"
    end
  end
end