打印 哈希 值 和 CSV 输出 RUBY

vfh0ocws  于 2022-11-22  发布在  Ruby
关注(0)|答案(1)|浏览(160)

我正在学习Ruby,我需要CSV文件的帮助。我没有找到正确的方法来打印输出到CSV文件,但我得到了递归,我不想这样。这是代码:

require "httparty"
require "csv"

class ConnexioEPPO
    include HTTParty
    base_uri 'https://data.eppo.int/api/rest/1.0'
    @@authtoken = "a9505d2ab257987580641d1a56de1f6c"

    def pests(eppocode)
        request = self.class.get("/taxon/#{eppocode}/pests?authtoken=#{@@authtoken}")
        result = request.parsed_response

        CSV.open("data.csv", "w", headers: result["Host"].first.keys) do |csv|
            result["Host"].each do |h|
                requestTax = self.class.get("/taxon/#{h["eppocode"]}/taxonomy?authtoken=#{@@authtoken}")
                resultTax = requestTax.parsed_response
                puts h["eppocode"]

                resultTax.each do |tax|
                    puts "#{tax["eppocode"]} #{tax["prefname"]}"
                    
                    planta = h.values << tax["eppocode"] +", "+ tax["prefname"]
                    csv << planta 
                end
            end
        end
    end
end

connexioEPPO = ConnexioEPPO.new
puts connexioEPPO.pests('1ULMG')

正如你可以看到在代码的第一部分im requesting(害虫)一个信息作为一个哈希包含什么(这只是几行):

{"eppocode"=>"ANIDMA", "idclass"=>9, "labelclass"=>"Host", "fullname"=>"Anisandrus maiche"}
{"eppocode"=>"ANOLGL", "idclass"=>9, "labelclass"=>"Host", "fullname"=>"Anoplophora glabripennis"}
{"eppocode"=>"APRIGE", "idclass"=>9, "labelclass"=>"Host", "fullname"=>"Apriona germari"}
{"eppocode"=>"PHYPUL", "idclass"=>9, "labelclass"=>"Host", "fullname"=>"'Candidatus Phytoplasma ulmi'"}

然后,我再次请求(分类)信息,我所做的是获取字段eppocode等于新请求中的eppocode的信息(想法是通过eppocode获取以前请求的字段的分类)
我们的想法是在CSV中打印出第一个标题{"eppocode"=>"ANIDMA", "idclass"=>9, "labelclass"=>"Host", "fullname"=>"Anisandrus maiche"},并添加相应字段的分类
所需输出(一个eppocode示例):

ANIDMA,9,Host,Anisandrus maiche,"1ANIMK, Animalia","1ARTHP, Arthropoda","1INSEC, Insecta","1COLEO, Coleoptera","1CURCF, Curculionidae","1SCOLS, Scolytinae","1ANIDG, Anisandrus","ANIDMA, Anisandrus maiche"

实际输出(一个eppocode示例):

ANIDMA,9,Host,Anisandrus maiche,"1ANIMK, Animalia"
ANIDMA,9,Host,Anisandrus maiche,"1ARTHP, Arthropoda"
ANIDMA,9,Host,Anisandrus maiche,"1HEXAQ, Hexapoda"
ANIDMA,9,Host,Anisandrus maiche,"1INSEC, Insecta"
ANIDMA,9,Host,Anisandrus maiche,"1COLEO, Coleoptera"
ANIDMA,9,Host,Anisandrus maiche,"1CURCF, Curculionidae"
ANIDMA,9,Host,Anisandrus maiche,"1SCOLS, Scolytinae"
ANIDMA,9,Host,Anisandrus maiche,"1ANIDG, Anisandrus"
ANIDMA,9,Host,Anisandrus maiche,"ANIDMA, Anisandrus maiche"

我想避免的是一堆字段与相同的信息。我希望你能理解我的问题,谢谢!

yvgpqqbh

yvgpqqbh1#

我认为,为了用最少的更改来修复代码,您需要将发布更改为CSV,使其位于resultTax循环之外,因此类似以下内容可能会起作用?:

planta = h.values
resultTax.each do |tax|
  puts "#{tax["eppocode"]} #{tax["prefname"]}"
  planta << tax["eppocode"] +", "+ tax["prefname"]
end
csv << planta

相关问题