【问题标题】:How do i create a c# dictionary that will read in key and values from .csv file我如何创建一个从 .csv 文件中读取键和值的 c# 字典
【发布时间】:2015-11-20 19:24:23
【问题描述】:

我有一个 .csv 文件,其中包含缩写列表及其实际含义,例如

大声笑出来,哈哈

我需要能够在文本框中搜索缩写词并将缩写词替换为实际单词。到目前为止,这是我试图理解字典但无法弄清楚如何从文件中读取值的方法。

 Dictionary<string, string> Abbreviations = new Dictionary<string, string>();
 Abbreviations.Add("Laughing Out Loud", "lol");
 foreach (KeyValuePair<string, string> abbrev in Abbreviations)
 {
     txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
 }

【问题讨论】:

  • 你有什么尝试从文件中读取值?

标签: c# csv dictionary visual-studio-2015


【解决方案1】:

您可以试试这个LINQ 解决方案GroupBy 用于处理密钥在文件中多次出现的情况。

  Dictionary<string, string[]> result =
     File.ReadLines("test.csv")
    .Select(line => line.Split(','))
    .GroupBy(arr => arr[0])
    .ToDictionary(gr => gr.Key,
                  gr => gr.Select(s => s[1]).ToArray());

检查TextBox中的缩写是否存在于Dictionary中:

foreach (KeyValuePair<string, string[]> abbrev in result)
{
    if (txtinput.Text == abbrev.Value)
    {
        txtinput.Text = txtinput + "<<" + abbrev.Key + ">>";
    }
}

【讨论】:

  • 我如何调用它并将其应用于在文本框中输入的文本?
  • 查看我添加的示例。
【解决方案2】:

您可以首先为您的文件创建一个 Stream Reader,然后循环获取 CSV 中的所有值并将它们添加到字典中。

static void Main(string[] args)
{
    var csv_reader = new StreamReader(File.OpenRead(@"your_file_path"));

    //declare your dictionary somewhere outside the loop.

    while (!csv_reader.EndOfStream)
    {
       //read the line and split if you need to with .split('')
        var line = reader.ReadLine();           

       //Add to the dictionary here

    }

   //Call another method for your search and replace. 
   SearchAndReplace(your_input)
}

然后实现该方法,搜索输入是否存在于字典中,是否替换它。

您可以使用 LINQ 将 csv 的值放入您的字典中,如果这对您来说更容易的话。

【讨论】:

    【解决方案3】:

    我将假设您的输入文件在实际文本中可能包含逗号,而不仅仅是分隔两个字段。

    现在,如果是这样的话,那么标准的 CSV 文件格式可以像这样格式化文件:

    Laughing Out Loud,LOL
    "I Came, I Saw, I Conquered",ICISIC
    

    但是,从您的示例中,您在“LOL”之前有一个 空格,因此您似乎没有使用标准 CSV。

    所以我会处理这个输入:

    Laughing Out Loud, LOL
    "I Came, I Saw, I Conquered",ICISIC
    "to, too, or two", 2
    because,B/C
    

    对于这个输入,这段代码会产生一个字典:

    var dictionary =
    (
        from line in File.ReadAllLines("FILE.CSV")
        let lastComma = line.LastIndexOf(',')
        let abbreviation = line.Substring(lastComma + 1).Trim()
        let actualRaw = line.Substring(0, lastComma).Trim()
        let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
            ? actualRaw.Substring(1, actualRaw.Length - 2)
            : actualRaw
        select new { abbreviation, actual }
    ).ToDictionary(x => x.abbreviation, x => x.actual);
    

    不过,你可以比这更好。很有可能创建一个“超级功能”,它会一次性为您完成所有替换。

    试试这个:

    var translate =
    (
        from line in File.ReadAllLines("FILE.CSV")
        let lastComma = line.LastIndexOf(',')
        let abbreviation = line.Substring(lastComma + 1).Trim()
        let actualRaw = line.Substring(0, lastComma).Trim()
        let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
            ? actualRaw.Substring(1, actualRaw.Length - 2)
            : actualRaw
        select (Func<string, string>)(x => x.Replace(abbreviation, actual))
    ).Aggregate((f1, f2) => x => f2(f1(x)));
    

    那么我可以这样做:

    Console.WriteLine(translate("It was me 2 B/C ICISIC, LOL!"));
    

    我得到这个结果:

    我也是,或者两个,因为我来了,我看到了,我征服了,大声笑了!

    【讨论】:

    • 这与我最终采用的方法非常相似,感谢您的帮助!
    • @smithcommajohn - 不用担心。然后你应该投票并打勾作为答案。干杯。
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 2015-10-01
    • 2020-02-06
    • 2017-05-01
    • 2017-03-06
    • 2022-11-26
    • 2013-03-02
    相关资源
    最近更新 更多