Ruby 转置 csv

标签 ruby csv transpose

我正在使用 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/

相关文章:

javascript - 使用javascript压缩xhtml客户端?

ruby - Ruby 脚本可以告诉它在哪个目录中吗?

java - 如何写入 CSV 文件的新行

sql-server-2008 - 透视动态列,无聚合

regex - 语法错误: (irb):4: invalid pattern in look-behind (positive look-behind/ahead)

python - 将字典添加到csv文件

json - 将数据 (.csv/json) 与 topojson 相结合

haskell - 代码在 Elm 中编译,但在 Haskell 中不编译

c++ - 矩阵矩形部分转置Cuda

mysql - 如何在 Rails find 中显示集合中的下一行