我正在使用 ruby 和 gem nokogiri 将 html 转换为 csv,效果很好,但我也想转置数据。
我知道 ruby 有一个我可以利用的转置函数,但我不确定如何将它集成到我正在使用的脚本中,因为我不太擅长 ruby。
有人可以帮我将转置代码放在该脚本中的正确位置以获得所需的效果吗?
require 'rubygems'
require 'nokogiri'
print_header_lines = ARGV[1]
File.open(ARGV[0]) do |f|
table_string=f
doc = Nokogiri::HTML(table_string)
doc.xpath('//table//tr').each do |row|
if print_header_lines
row.xpath('th').each do |cell|
print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
end
end
row.xpath('td').each do |cell|
print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
end
print "\n"
end
end
根据我在网上找到的信息,转置的脚本如下所示:
require 'CSV'
rows = CSV.new($stdin).read
puts rows.transpose.map { |x| x.join ',' }
当然,要求需要放在顶部,但我不确定在上面的示例中要更改什么才能获得输出转置。
提前非常感谢。
最佳答案
如果你想使用转置,你需要一个二维数组。目前您只是一次打印一行。为此使用 map :
tbl_array = doc.xpath('//table//tr').map do |row|
row.xpath('td').map do |cell|
"\" #{cell_text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1')} \", "
end
end
tbl_array.transpose.each do |row|
row.each { |cell| print cell }
end
关于Ruby 转置 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29521170/