【问题标题】:How to parsegju,jk如何在 C# 中使用 CSV 帮助器解析 TSV 文件?
【发布时间】:2021-10-08 18:26:10
【问题描述】:

我必须解析一个具有以下结构的 TSV 文件:

[Section one of info]
"Atr1    1"
"Atr2    2"
[Section two of info]
"Atr3    Atr4"
"1    2"
"2    3"
"4    5"

Atr3Atr4 是对象的一部分,并且会有一个值列表。我需要使用CsvHelper 在 C# 中实现它。谁能给我一个简短的开始?

【问题讨论】:

  • 不知道为什么这被否决了,但它可能与使用图像而不是示例数据的格式化文本有关。
  • stackoverflow.com/questions/60474975/… 的可能重复无论哪种方式,在阅读器配置中,您都可以将分隔符设置为您想要的任何内容,在您的情况下为“\t”
  • 我设法将 CSV 信息设置为代码。谢谢!
  • [Section one of info][Section two of info] 是 CSV 文件的一部分吗?如果没有,这两个部分之间是否有任何分隔符?另外,每一行都像这样用双引号括起来是真的吗? "1 2"?
  • @dbc 是的,它们是 CSV 文件的一部分,关于双引号,这是我尝试用记事本打开文件时得到的结果

标签: c# .net csvhelper


【解决方案1】:

我不确定这是否是您想要做的。我还注意到记录之间似乎有 4 个空格。如果真的是制表符,可以把分隔符改成制表符Delimiter = "\t",

void Main()
{
    var data = @"[Section one of info]
""Atr1    1""
""Atr2    2""
[Section two of info]
""Atr3    Atr4""
""1    2""
""2    3""
""4    5""";

    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        Delimiter = "    ",
        Mode = CsvMode.Escape
    };

    using (var reader = new StringReader(data))
    using (var csv = new CsvReader(reader, config))
    {
        var isSectionOne = true;
        var record = new Foo() { Atr3 = new List<int>(), Atr4 = new List<int>() };
        
        while(csv.Read())
        {
            if (csv.GetField(0).StartsWith("["))
                continue;
                
            if (isSectionOne)
            {
                if (csv.GetField(0) == "Atr1")
                {
                    record.Atr1 = csv.GetField<int>(1);
                }
                if (csv.GetField(0) == "Atr2")
                {
                    record.Atr2 = csv.GetField<int>(1);
                }
                if (csv.GetField(0) == "Atr3")
                {
                    isSectionOne = false;
                }
            }
            else
            {
                record.Atr3.Add(csv.GetField<int>(0));
                record.Atr4.Add(csv.GetField<int>(1));
            }           
        }
        record.Dump();
    }
}

public class Foo
{
    public int Atr1 { get; set; }
    public int Atr2 { get; set; }
    public List<int> Atr3 { get; set; }
    public List<int> Atr4 { get; set; }
}

【讨论】:

  • 感谢您的帮助,这非常有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多