gpt4 book ai didi

ruby - 如何进一步处理导致 Ruby FasterCSV 库抛出 MalformedCSVError 的数据行?

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:19 25 4
gpt4 key购买 nike

传入的数据文件包含格式错误的 CSV 数据,例如未转义的引号,以及(有效的)CSV 数据,例如包含新行的字段。如果检测到 CSV 格式错误,我想对该数据使用替代例程。

使用以下示例代码(为简单起见缩写)

FasterCSV.open( file ){|csv|
row = true
while row
begin
row = csv.shift
break unless row
# Do things with the good rows here...

rescue FasterCSV::MalformedCSVError => e
# Do things with the bad rows here...
next
end
end
}

MalformedCSVError 是在 csv.shift 方法中引起的。如何访问导致 rescue 子句错误的数据?

最佳答案

require 'csv' #CSV in ruby 1.9.2 is identical to FasterCSV

# File.open('test.txt','r').each do |line|
DATA.each do |line|
begin
CSV.parse(line) do |row|
p row #handle row
end
rescue CSV::MalformedCSVError => er
puts er.message
puts "This one: #{line}"
# and continue
end
end

# Output:

# Unclosed quoted field on line 1.
# This one: 1,"aaa
# Illegal quoting on line 1.
# This one: aaa",valid
# Unclosed quoted field on line 1.
# This one: 2,"bbb
# ["bbb", "invalid"]
# ["3", "ccc", "valid"]

__END__
1,"aaa
aaa",valid
2,"bbb
bbb,invalid
3,ccc,valid

只需将文件逐行输入 FasterCSV 并修复错误。

关于ruby - 如何进一步处理导致 Ruby FasterCSV 库抛出 MalformedCSVError 的数据行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com