2

我从 SQL 导出表和查询,其中一些字段是多行的。

读取 CSV 的 Ruby(1.9+)方法似乎是:

require 'csv'

CSV.foreach("exported_mysql_table.csv", {:headers=>true}) do |row|
    puts row
end

如果我的数据是这样的,那效果很好:

"id","name","email","potato"
1,"Bob","bob@bob.bob","omnomnom"
2,"Charlie","char@char.com","andcheese"
4,"Doug","diggyd@diglet.com","usemeltattack"

(第一行是标题/属性)

但如果我有:

"id","name","address","email","potato"
1,"Bob","--- 
- 101 Cottage row
- Lovely Village
- \"\"
","bob@bob.bob","omnomnom"
2,"Charlie","--- 
- 102 Flame Street
- \"\"
- \"\"
","char@char.com","andcheese"
4,"Doug","--- 
- 103 Dark Cave
- Next to some geo dude
- So many bats
","diggyd@diglet.com","usemeltattack"

然后我得到错误:

.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/csv.rb:1894:in `block (2 levels) in shift': Missing or stray quote in line 2 (CSV::MalformedCSVError)

这似乎是因为该行的末尾没有关闭引号,因为它跨越了几行。

(我尝试了“FasterCSV”,自 ruby​​ 1.9 以来,该 gem 变成了“csv”)

4

1 回答 1

5

您的问题不是多行而是格式错误的 CSV。

像这样替换\"行结束后的和结束空格:

require 'csv' 

ml = %q{"id","name","address","email","potato" 
1,"Bob","---  
- 101 Cottage row 
- Lovely Village 
- \"\" 
","bob@bob.bob","omnomnom" 
2,"Charlie","---  
- 102 Flame Street 
- \"\" 
- \"\" 
","char@char.com","andcheese" 
4,"Doug","---  
- 103 Dark Cave 
- Next to some geo dude 
- So many bats 
","diggyd@diglet.com","usemeltattack"}

ml.gsub!(/\" \n/,"\"\n").gsub!(/\\\"/,"__")

CSV.parse(ml, {:headers=>true}) do |row|
  puts row
end

这给出了:

"id","name","address","email","potato"
1,"Bob","---  
- 101 Cottage row 
- Lovely Village 
- ____
","bob@bob.bob","omnomnom"
etc

如果您无法控制提供 CSV 的程序,则必须打开文件、读取内容、进行替换,然后解析 CSV。我__在这里使用,但您可以使用其他不冲突的字符。

于 2012-10-16T17:02:44.633 回答