2013-10-10 18 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

謝謝。這有很大幫助。雖然它可以運行幾百行代碼,但它的統計數據只是一直保持縮進。 –