[英]F# Parsing CSV file - find which line is wrong
我从发现的一些资源中编写了此脚本。 它正在工作,但是我有一些文件有问题。 我是F#的新手,所以如何更改FileHelpersException的行以获取确切的行,问题出在哪里? 谢谢
// Learn more about F# at http://fsharp.net
// See the 'F# Tutorial' project for more help.
open FileHelpers
open System
[<DelimitedRecord(",")>]
type CsvRecord =
class
val field1 : string
val field2 : string
val field3 : int
new () = {
field1 = ""
field2 = ""
field3 = 0
}
end
[<EntryPoint>]
let main argv =
use file = System.IO.File.CreateText("result.txt")
let engine = new FileHelperEngine<CsvRecord>()
engine.Encoding <- new Text.UTF8Encoding()
let res =
try
engine.ReadFile("test.csv")
with
| :? FileHelpersException -> Array.empty<CsvRecord>
for record in res do
fprintfn file "%s" record.field1
printf "DONE!"
let s = Console.ReadLine()
0 // return an integer exit code
我建议您改用CsvTypeProvider 。 当不匹配时,错误消息会指出存在错误的行
open FSharp.Data
[<EntryPoint>]
let main argv =
use file = System.IO.File.CreateText("result.txt")
let csv = new CsvProvider<"test.csv">()
for record in csv.Data do
fprintfn file "%s" record.field1
如果要忽略有错误的行,只需将IgnoreErrors=true
作为额外参数传递给CsvProvider
这个问题是关于您正在使用的FileHelpers库的,而不是F#的,因此查看有关文档可能会有所帮助。 在这种情况下,您可以检查ConvertException
而不是FileHelpersException
,后者包含的成员为您提供有关该成员的更多详细信息。
try
engine.ReadFile("test.csv")
with
| :? ConvertException as ex ->
printfn "ERROR: Line %d Col %d" ex.LineNumber ex.ColumnNumber
Array.empty<CsvRecord>
我同意Gustavo的观点,但是您可能会发现使用CsvTypeProvider更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.