我有两个文本文件,并且它们具有一个相同的字段(PET)。我想组合两个文件并输出一个新文件包含三个字段(所有者宠物购买者)。我的代码主要取决于两个文件是否具有相同的PET(宠物的名称和宠物数),我将在新文件中将买方的名称添加到买家字段中。仅当两个文件与PET相同的申请时,它才能打印出来。
但是我的代码无法正常工作,需要一些帮助,谢谢。
input_file_1(.txt)
owner pet
Michael dog, cat
John pig, rabbit
Marry dog, cat
input_file_2(.txt)
buyer pet
Sean cat, dog
Mark cat, dog
Joy dog, mouse
Tina cat, dog
我希望结果看起来像这样:
owner pet buyer
Michael cat, dog Sean, Mark, Tina
Mary cat, dog Sean, Mark, Tina
我的代码看起来像这样:
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
我建议您将pet
用作密钥:
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