如何读取无标题的CSV [英] How to read a CSV with no headers

查看:90
本文介绍了如何读取无标题的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下数据的CSV(无标题)

I have a CSV with the following data (no header)

12,2010,76
2,2000,45
12,1940,30

并且我正在使用以下 CSVReader 阅读

and I'm using the following CSVReader to read

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class CSVReader
{
    static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
    static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
    static char[] TRIM_CHARS = { '\"' };

    public static List<Dictionary<string, object>> Read(string file)
    {
        var list = new List<Dictionary<string, object>>();
        TextAsset data = Resources.Load (file) as TextAsset;

        var lines = Regex.Split (data.text, LINE_SPLIT_RE);

        if(lines.Length <= 1) return list;

        var header = Regex.Split(lines[0], SPLIT_RE);
        for(var i=1; i < lines.Length; i++) {

            var values = Regex.Split(lines[i], SPLIT_RE);
            if(values.Length == 0 ||values[0] == "") continue;

            var entry = new Dictionary<string, object>();
            for(var j=0; j < header.Length && j < values.Length; j++ ) {
                string value = values[j];
                value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
                object finalvalue = value;
                int n;
                float f;
                if(int.TryParse(value, out n)) {
                    finalvalue = n;
                } else if (float.TryParse(value, out f)) {
                    finalvalue = f;
                }
                entry[header[j]] = finalvalue;
            }
            list.Add (entry);
        }
        return list;
    }
}

问题是此CSVReader使用List<Dictionary<string, object>>,因此,如果没有标题信息,则字典键将变为null或(不太可能)为空字符串.在字典中添加条目时,这两种情况都将导致引发异常.

The problem is this CSVReader uses List<Dictionary<string, object>> and so if there is no header information, the dictionary keys become either null or (less likely) an empty string. Both of these cases would lead to exception throwing when adding entries to the dictionary.

我可以将标题添加到CSV文件,但这不是理想的解决方案.

I can add the headers to the CSV file but that isn't the ideal solution.

推荐答案

首先,几乎可以肯定有很多现成的库可用于此任务,它们可能在NuGet上可用.其中之一可能是更好的解决方案.

Firstly, there are almost certainly lots of ready-made libraries you could use for this task, which are probably available on NuGet. One of those might well be a better solution.

尽管如此,使用已有的方法,您可以制作该方法的替代版本,该方法返回简单的对象列表,并从中删除填充标头的代码.像这样的东西(未经测试,但我认为它应该可以工作):

Nevertheless, working with what you've got already you could make an alternative version of the method which returns a simple list of objects, and remove the code from it which populates the headers. Something like this (untested, but I think it should work):

public static List<List<object>> ReadWithoutHeader(string file)
{
    var list = new List<List<object>>();
    TextAsset data = Resources.Load (file) as TextAsset;
    var lines = Regex.Split (data.text, LINE_SPLIT_RE);

    if(lines.Length <= 1) return list;

    for(var i=0; i < lines.Length; i++) {

        var values = Regex.Split(lines[i], SPLIT_RE);
        if(values.Length == 0 ||values[0] == "") continue;
        var entry = new List<object>();

        for(var j=0; j < values.Length; j++ ) {
            string value = values[j];
            value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
            object finalvalue = value;
            int n;
            float f;
            if(int.TryParse(value, out n)) {
                finalvalue = n;
            } else if (float.TryParse(value, out f)) {
                finalvalue = f;
            }
            entry.Add(finalvalue);
        }
        list.Add(entry);
    }
    return list;
}

这篇关于如何读取无标题的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆