作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我想用 ruby 打印一个 CSV 文件,但我想对其进行格式化。有没有办法在层次结构意义上格式化数据?这是我需要检查的列表的一小部分:
,"11: Agriculture, Forestry, Fishing and Hunting",,
,,"111: Crop Production",
,,,"111110: Soybean Farming"
,,,"111120: Oilseed (except Soybean) Farming"
,,,"111130: Dry Pea and Bean Farming"
,,,"111140: Wheat Farming"
,,"112: Animal Production",
,,,"112111: Beef Cattle Ranching and Farming"
,,,"112112: Cattle Feedlots"
,,,"112120: Dairy Cattle and Milk Production"
,,,"112130: Dual-Purpose Cattle Ranching and Farming"
我的代码是:
require 'csv'
col_data = []
CSV.foreach("primary_NAICS_code.txt") {|row| col_data << row}
puts col_data
这只会打印出所有内容。它是数组中的数组吗?像这样的东西:
CSV.foreach do |row|
row.each do |line|
puts line
end
end
任何帮助都会为我指明正确的方向。
我想把信息格式化成这样:
|_ <~~ row 1 column 1
| |__<~ row 1 column 2
| | |__<~row 2 column 2
| | | |__
| | | | |__ etc...
| | | | | |__
最佳答案
由于您的数据已经缩进,您只需对其进行转换/格式化。这样的事情应该有效:
col_data.each do |row|
indentation, (text,*) = row.slice_before(String).to_a
puts indentation.fill("|").join(" ") + "_ " + text
end
输出:
|_ 11: Agriculture, Forestry, Fishing and Hunting
| |_ 111: Crop Production
| | |_ 111110: Soybean Farming
| | |_ 111120: Oilseed (except Soybean) Farming
| | |_ 111130: Dry Pea and Bean Farming
| | |_ 111140: Wheat Farming
| |_ 112: Animal Production
| | |_ 112111: Beef Cattle Ranching and Farming
| | |_ 112112: Cattle Feedlots
| | |_ 112120: Dairy Cattle and Milk Production
| | |_ 112130: Dual-Purpose Cattle Ranching and Farming
关于ruby-on-rails - 在 ruby 中遍历 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19297646/
我是一名优秀的程序员,十分优秀!