F#
我有兴趣读取 csv 文件并输出 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 文件来定义类型。
https://joshclose.github.io/CsvHelper/
http://www.filehelpers.net/example/QuickStart/ReadWriteRecordByRecord/
http://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">
但是输入文件的列数可能会发生变化(因此我无法定义抽象类)
当然,我可以编写正则表达式来逐行分解输入文件,但我有兴趣知道其他人是否已经这样做了(或者它是标准库函数)。
谢谢。
最佳答案
如果您使用FSharp.Data
,则有一个CsvFile
类可以读取任意CSV 文件。
例如
let csv = CsvFile.Load(filename, hasHeaders = true)
csv.Rows
|> Seq.map (fun r -> (r.["Image"], float r.["Size"]))
将从“图像”和“大小”列创建元组序列。
csv.Headers
是一个string[] 选项
,其中包含文件第一行的标题。
let csv = CsvFile.Load(filename, hasHeaders = false)
csv.Rows
|> Seq.map (fun r -> r.Columns |> List.ofArray)
|> List.ofSeq
可能就是你想要的
关于csv - F# 中读取 csv 文件的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45412423/