通过Ruby和CSV打印出多级无序列表

时间:2013-10-10 20:53:42

标签: html ruby csv

这可能是一种倒退的方式。我有一些代码读取CSV文件并将结果打印在HTML文件中。如果可能的话,我想将此文件打印为无序列表。

这就是我现在所拥有的,它的输出不是我想要的:

require 'csv'

 col_data = [] 
 CSV.foreach("primary_NAICS_code.txt") {|row| col_data << row} 

begin
  file = File.open("primary_NAICS_code_html.html", "w")
  col_data.each do |row|
    indentation, (text,*) = row.slice_before(String).to_a
    file.write(indentation.fill("<ul>").join(" ") + "<il>" + text+ "</il></ul?\n")
  end
rescue IOError => e
 puts e
ensure
  file.close unless file == nil
end

1 个答案:

答案 0 :(得分:1)

  • 无序列表未被<ul> ... </ul?包围。问号不会使HTML感到满意。
  • 列表项是<li>代码,而不是<il>
  • 您需要跟踪深度,以了解是否需要添加<ul>标记,或者只需添加更多项目。

试试这个:

require 'csv'

col_data = [] 
 CSV.foreach("primary_NAICS_code.txt") {|row| col_data << row} 

begin
  file = File.open("primary_NAICS_code_html.html", "w")
  file.write('<ul>')
  depth = 1
  col_data.each do |row|
    indentation, (text,*) = row.slice_before(String).to_a
    if indentation.length > depth
      file.write('<ul>')
    elsif indentation.length < depth
      file.write('</ul>')
    end
    file.write("<li>" + text+ "</li>")
    depth = indentation.length
  end
  file.write('</ul>')
rescue IOError => e
  puts e
ensure
  file.close unless file == nil
end

它不是很漂亮,但似乎有效。

相关问题