2013-10-10 19 views
0

这可能是一个倒退的方法。我有一些代码读取CSV文件并将结果打印在HTML文件中。如果可能的话,我希望将这个文件打印成无序列表。通过Ruby和CSV打印出多级无序列表

这是我现在有它的输出是不是我想要的:

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 
+0

输出是什么样的?你想如何看待?如何处理一些示例CSV? “关于您编写​​的代码问题的问题必须在问题本身中描述具体问题 - 并包含有效代码以再现问题本身。请参阅http://SSCCE.org以获取指导。” –

回答

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 

这不是很漂亮,但它似乎工作。

+0

谢谢。这有很大帮助。虽然它可以运行几百行代码,但它的统计数据只是一直保持缩进。 –