代码之家  ›  专栏  ›  技术社区  ›  SantiClaus

如何用f_编写csv?

f#
  •  3
  • SantiClaus  · 技术社区  · 8 年前

    我如何将f格式的记录写入csv?对于某个变量的每个实例,最好有一行。我的记录和最终输出是一个类似下面的地图。

    type Family =
        { Month : int
          Year : int
          Income : float
          Family : int
          Dogs : int
          Cats : int
        }
    
    let monthly =
        timeMap
        |> Seq.ofList
        |> Seq.map(fun ((month,year), rows) ->
            { Month = month
              Year = year
              Income = rows.Inc
              Family = familyMap.[(month,year)].Children
              Dogs = familyMap.[(month,year)].Dogs
              Cats = familyMap.[(month,year)].Cats
            })
        |> List.ofSeq
    
    let map = 
        monthly
        |> List.map (fun x -> (x.Year,x.Month),x)
        |> Map.ofList 
    

    编辑

    这是我试过的,但我错了 (A,B,C,D,E,F) are not defined ,而且 it is recommended that I use the syntax new (type) args .最后一个错误出现在 >> MyCsvType

    type MyCsvType = CsvProvider<Schema = "A (int), B (int), C (float), D (int), E (int), F (int)", HasHeaders = false>
    let myCsvBuildRow (x:Family) = MyCsvType.Row(x.A,x.B,x.C,x.D,x.E,x.F)
    let myCsvBuildTable = (Seq.map myCsvBuildRow) >> Seq.toList >> MyCsvType
    let myCsv = monthly|> myCsvBuildTable
    myCsv.SaveToString()
    
    1 回复  |  直到 8 年前
        1
  •  5
  •   Tomas Petricek    8 年前

    你的代码就快到了,除了 myCsvBuildRow 函数需要访问 Family 用正确的名字打字。在您的版本中,您正在访问诸如 A 我是说, B ,等等,但这些是csv文件中列的名称,而不是f记录成员的名称。以下是我的窍门:

    type MyCsvType = CsvProvider<Schema = "A (int), B (int), C (float), D (int), E (int), F (int)", HasHeaders = false>
    
    let myCsvBuildRow (x:Family) = 
      MyCsvType.Row(x.Month,x.Year,x.Income,x.Family,x.Dogs,x.Cats)
    let myCsvBuildTable data = 
      new MyCsvType(Seq.map myCsvBuildRow data)
    
    let myCsv = family |> myCsvBuildTable
    myCsv.SaveToString()