简体   繁体   English

F#-CSV至两键字典

[英]F# - CSV to two keys dictionary

I have localization CSV file with following structure 我具有以下结构的本地化CSV文件

Key, Language1, Language2, Language3
some key, translation1, translation2, translation3

I'd like to write function that return multidimensional array from what I can easy get translation. 我想编写从我可以轻松获得转换的函数中返回多维数组的函数。 Eg 例如

translations["some key"]["Language1"] returns me "translation1" translations["some key"]["Language1"]返回我“ translation1”

I wrote only loading of file 我只写了文件的加载

open GleedsSnags.Localization
open FSharp.Data

type Loc = CsvProvider<"Localization.csv">
let locData = Loc.Load("Localization.csv")

but I don't know what data structure is best for this issue and how to construct result in F# in most elegant way. 但是我不知道哪种数据结构最适合此问题,以及如何以最优雅的方式在F#中构造结果。 Then I'd like to read this structure in C#. 然后,我想用C#阅读此结构。

Any idea? 任何想法?

Using type providers you can achieve the following easily: 使用类型提供程序可以轻松实现以下目的:

open FSharp.Data

type Loc = CsvProvider<"Localization.csv">

let myMap = Loc.Rows |> Seq.map (fun r -> r.Key, r) |> Map.ofSeq

// accessing translations:
let trans1 = myMap.["some key"].Language1
let trans2 = myMap.["some key"].Language2

Here the type of each row in the map is generated by the type provider and it may cause trouble when passing the result around between different libraries. 此处,映射中的每一行的类型都是由类型提供程序生成的,在不同库之间传递结果时可能会造成麻烦。

On the other hand, there is also another tool for dealing with CSV files in the FSharp.Data module, namely CsvFile : 另一方面,FSharp.Data模块中还有另一个用于处理CSV文件的工具,即CsvFile

open FSharp.Data

let csv = CsvFile.Load("Localization.csv")
// To use the dynamic operator '?'
open FSharp.Data.CsvExtensions
// For Dictionary
open System.Collections.Generic

let myMap2 = csv.Rows |> Seq.map (fun r -> r?Key, r) |> Map.ofSeq 
let dict  = Dictionary(myMap2)

Now you have a dictionary of type Dictionary<string,CsvRow> that can be accessed as follows: 现在您有了一个Dictionary<string,CsvRow>类型的Dictionary<string,CsvRow> ,可以按以下方式访问它:

dict.["some key"].["Language1"]

First of all: https://msdn.microsoft.com/en-us/library/h6270d0z(v=vs.110).aspx 首先: https : //msdn.microsoft.com/en-us/library/h6270d0z(v=vs.110).aspx

If you need to do it this way, you have your files and may possibly do something like: 如果您需要这样做,则可以拥有文件,并且可能会执行以下操作:

let translation key language = 
 let d = 
  locData
  |> Seq.filter(fun x -> x.Key = key)
  |> Seq.exactlyone
 d.[language]

To speed stuff up, use some Map or something: 为了加快速度,请使用一些Map或其他工具:

let mapLocData = 
 locData 
 |> Seq.groupBy (fun x -> x.Key)
 |> Map.ofSeq

let translation key language = 
  mapLocData.[key].[language]

...ish... ... ... ISH

code not at all tested, and only written here etc. 代码根本没有经过测试,仅在此处编写等。

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

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