我正在解析从 FTP 站点提取的 CSV 文件。我想解析 CSV 并提取一些特定字段以存储在数据库中。我遇到一些我不理解的编码,并且我相信 CSV.parse 也不期望这种编码:
filename = "#{RAILS_ROOT}/spec/files/20120801.01.001.CSV"
filestream = File.new(filename, "r")
while (line = filestream.gets)
puts "line: #{line}"
CSV.parse(line) do |row|
case row[0]
when "RH"
# do something
when "SH"
#do something else
end
end
end
CSV 文件中的第一行如下所示:
"\376\377\000\"\000R\000H\000\"\000,\0002\0000\0004\0005\000/\0000\0008\000/\0000\0002\000 \0000\0005\000:\0005\0007\000:\0002\0001\000 \000-\0000\0007\0000\0000\000,\0002\0000\0001\0002\000/\0000\0008\000/\0000\0001\000 \0000\0000\000:\0000\0000\000:\0000\0000\000 \000-\0000\0004\0000\0000\000,\0002\0000\0001\0002\000/\0000\0008\000/\0000\0001\000 \0002\0003\000:\0005\0009\000:\0001\0004\000 \000-\0000\0007\0000\0000\000,\000\"\000Y\0003\000B\0003\0003\000Z\000N\000K\000A\000U\000B\000H\000N\000\"\000,\0000\0000\0001\000,\000\n"
我有一个自己创建的不同 CSV 文件,它以人类可读的文本形式打印出来。我在这里缺少什么?在传递给 CSV.parse 之前,我是否需要对 CSV 字符串应用一些编码?
这是堆栈跟踪:
CSV::IllegalFormatError
/Users/project/app/models/parse_csv.rb:5:in `parse'
我现在被迫使用 ruby v1.8.7。
我知道我可以使用 CSV.open,但我有意尝试向 CSV.parse 提供 IO 流,以便我可以使用 SFTP 从 FTP 站点抓取 CSV 文件,将文件流式传输到内存中,而无需存储将 CSV 文件写入磁盘:
sftp.open_handle("/path/to/remote.file") do |handle|
data = sftp.read(handle)
end
预先感谢您的任何想法!
最佳答案
该行包含双引号,可能需要转义。我发现this在 ruby-forum.com 上。
It's just a guess, but maybe you could try replacing every double-quote character that isn't either preceded or followed by a comma with a single quote? Something like the untested code below:
line.gsub(/[^,]"[^,]/,"'")
It would probably require reading the whole file first, writing out a corrected version, and then calling the CSV methods on that, but it beats doing it by hand :).
另外,顺便说一句,我认为而不是
while (line = filestream.gets)
你可以做
filestream.gets.each_line 做 |line|
哪个可能更红(也许?)
关于Ruby:CSV 编码:IlegalFormatError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11788010/