简体   繁体   English

F#解析CSV文件-查找错误的行

[英]F# Parsing CSV file - find which line is wrong

I wrote this script from some resources I found. 我从发现的一些资源中编写了此脚本。 It's working but I some files I have problem. 它正在工作,但是我有一些文件有问题。 I am new in F# so how can I change line with FileHelpersException to get exact line where is the problem? 我是F#的新手,所以如何更改FileHelpersException的行以获取确切的行,问题出在哪里? Thanks 谢谢

// 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

I suggest that you use CsvTypeProvider instead. 我建议您改用CsvTypeProvider When there's a mismatch the error message states the line which has the error 当不匹配时,错误消息会指出存在错误的行

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

If you want to ignore the lines with errors, just pass IgnoreErrors=true as an extra parameter to CsvProvider 如果要忽略有错误的行,只需将IgnoreErrors=true作为额外参数传递给CsvProvider

This question is about the FileHelpers library you are using, not F#, so looking at the docs for that might help. 这个问题是关于您正在使用的FileHelpers库的,而不是F#的,因此查看有关文档可能会有所帮助。 In this case you can check for ConvertException instead of FileHelpersException , which contains members that give you more details about the member. 在这种情况下,您可以检查ConvertException而不是FileHelpersException ,后者包含的成员为您提供有关该成员的更多详细信息。

try
    engine.ReadFile("test.csv")
with
    | :? ConvertException as ex ->
        printfn "ERROR: Line %d Col %d" ex.LineNumber ex.ColumnNumber
        Array.empty<CsvRecord>

I agree with Gustavo though, you might find it easier to use the CsvTypeProvider. 我同意Gustavo的观点,但是您可能会发现使用CsvTypeProvider更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM