用于在F#中读取csv文件的库

编程入门 行业动态 更新时间:2024-10-26 16:29:22
本文介绍了用于在F#中读取csv文件的库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

F#

我有兴趣读取一个csv文件并输出一个List<列表<字符串>>

I am interested to read a csv file and output a List< List< string > >

let readCsv (filepath:string) : string list list = //....................... input file: Quote1,Quote2,Quote3 "Hello,World","He said:""Yes""",Example Output: // Type: string list list [["Quote1";"Quote2";"Quote3"]; ["Hello,World"; "He said:"Yes"";"Example"]] Input2: 1,2,3,4,5,6 7,8,9,10,11,12 Output2: // Type: string list list [["1";"2";"3";"4";"5";"6"]; ["7";"8";"9";"10";"11";"12"]]

但是,某些Nuget软件包,例如CsvHelper,FileHelper,F#Data依赖于定义一个类来捕获"数据,或者通过引用一个csv文件来定义类型.

However, some of the Nuget packages, e.g. CsvHelper, FileHelper, F#Data relies on defining a Class to "capture" the data, or defining a type by referring to a csv file.

joshclose.github.io/CsvHelper/

www.filehelpers/example/QuickStart/ReadWriteRecordByRecord/

fsharp.github.io/FSharp.Data/index.html

例如:

// In C#, from FileHelper Documentation [DelimitedRecord(",")] public class AbstractClass { public string Quote1; public string Quote2; public string Quote3; }

// F# Data Documentation type AbstractType = CsvProvider<"../example.csv">

但是输入文件的列数可能会改变(因此我无法定义抽象类)

But the input file may change in number of columns (and so I cannot define an abstract class)

当然,我可以编写正则表达式来逐行分解输入文件,但是我很想知道是否有人已经做过(或者它是标准库函数).

Of course, I can just write regular expression to break up the input file line-by-line, but I am interested to know if someone else has already done it (or is it a standard library function).

谢谢.

推荐答案

如果使用FSharp.Data,则有一个CsvFile类可以读取任意CSV文件.

If you use FSharp.Data there's a CsvFile class which can read arbitrary CSV files.

例如

let csv = CsvFile.Load(filename, hasHeaders = true) csv.Rows |> Seq.map (fun r -> (r.["Image"], float r.["Size"]))

将在图像"和大小"列中创建一个元组序列.

Would create a sequence of tuples from the "Image" and "Size" columns.

csv.Headers是string[] option,其中包含文件第一行的标题.

csv.Headers is a string[] option which contains the headers from the first line of the file.

let csv = CsvFile.Load(filename, hasHeaders = false) csv.Rows |> Seq.map (fun r -> r.Columns |> List.ofArray) |> List.ofSeq

可能就是你所追求的

更多推荐

用于在F#中读取csv文件的库

本文发布于:2023-11-12 09:33:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   csv

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!