我正在學習 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')
正如您在代碼的第一部分中看到的那樣,我請求(害蟲)作為哈希包含的資訊(這只是幾行):
{"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"
我想要的是避免使用相同資訊的那一堆欄位。我希望你能理解我的問題謝謝!
uj5u.com熱心網友回復:
我相信,為了用最少的更改來修復您的代碼,您需要將發布到 CSV 的內容更改為在您的resultTax回圈之外,所以類似以下的內容可能有效?:
planta = h.values
resultTax.each do |tax|
puts "#{tax["eppocode"]} #{tax["prefname"]}"
planta << tax["eppocode"] ", " tax["prefname"]
end
csv << planta
(請原諒任何錯別字,從我的手機發布)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410003.html
標籤:
上一篇:使用迭代器生成csv行
