这可能是一种倒退的方式。我有一些代码读取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
答案 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
它不是很漂亮,但似乎有效。