【问题标题】:How to parse CSV-based IF conditions如何解析基于 CSV 的 IF 条件
【发布时间】:2017-08-31 03:08:08
【问题描述】:

我正在尝试解析我从 Nexpose 的 API 调用的 CSV 报告:

 nsc.list_reports.each do | report |
  puts report.name
  report_id = report.config_id
  report_summary = nsc.generate_report(report_id, true)

  report = nsc.download(report_summary.uri)
  puts report    


  csv = CSV.read(report, :headers => true, :converters => :all).select do|row|
    row['number available'] > 0 && row['Score'] >=9
  end

  csv.each do |row|
    puts row['name']
  end
end

但基本上这是它给我的格式

ID,name,title,Score,number available
1,"test1","title1",4,3
2,"test2","title2",8,0
3,"test3","title3",9,0
4,"test4","title4",10,6
5,"test5","title5",5,22
6,"test6","title6",9,1
7,"test7","title7",2,5

我的目标是只找到“分数”>=9 和“可用数量”>0 的那些。所以在这个例子中,它应该返回 'test4' 和 'test6'

【问题讨论】:

  • WHAT 您要解析 CSV 文件吗?请阅读“minimal reproducible example”和链接页面。我们需要演示问题的最小代码、支持演示问题的代码的最小输入 (CSV) 和预期输出。你给了我们预期的输出,但没有办法做到这一点。

标签: ruby csv rubygems


【解决方案1】:

不要将标题转换为符号;使用select,而不是detect;还有一些小细节:

csv = CSV.read(report, :headers => true, :converters => :all).select do|row|
   row['number available'] > 0 && row['Score'] >=9}
end    

csv.each do |row|
  puts row["name"]
end 

【讨论】:

  • 来自 C:/Ruby22-x64/lib/ruby/2.2.0/csv.rb:1256:in open' from C:/Ruby22-x64/lib/ruby/2.2.0/csv.rb:1256:in open' 来自 C:/Ruby22-x64/lib/ruby/2.2。 0/csv.rb:1330:in read' from C:/Users/1/RubymineProjects/nexpose/main.rb:26:in block in ' 来自 C:/Users/RubymineProjects/nexpose/main.rb:18:in each' from C:/Users/RubymineProjects/nexpose/main.rb:18:in ' 来自 - e:1:in load' from -e:1:in
    '
  • 尝试在 puts report 行之后复制粘贴此代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多