我有两个文本文件,它们有一个相同的字段(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
答案 0 :(得分:0)
我建议您使用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