본문 바로가기

TIL

[ 25.01.20 ] TIL - CSV 파싱

[ Unity ]

 

유니티에서 CSV 파일을 파싱하기 위한 방법 중 하나이다.

 

아래 스크립트를 프로젝트에 넣은 후, 파싱하고 싶은 CSV 파일을 Resources 폴더에 넣으면 된다.

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

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;
    }
}

 

새로운 스크립트에 아래 코드를 작성하면 data 변수에 CSV 파일을 파싱해서 저장할 수 있다.

List<Dictionary<string,object>> data = CSVReader.Read ("CSV_path");

for (var i = 0; i < data.count; i++)
{
	print(data[i]["Header"]);
}

 

원래 CSV 파일을 파싱하는 자체 코드를 시도했는데, 각 데이터의 마지막 Header가 제대로 파싱되지 않았다.

아무래도 개행문자와 관련된 예외 처리를 진행하지 않아서 발생한 오류인 것 같다.

 

CSVReader에서는 LINE_SPLIT_RE를 통해 CSV 파일에서 사용하는 모든 개행문자에 대해 처리한다.

 

출처

Lightweight CSV reader for Unity | Brave New Method