Advertisement
Guest User

CSVReader

a guest
Mar 7th, 2021
5,042
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 1 0
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Text.RegularExpressions;
  6.  
  7. public class CSVReader
  8. {
  9. static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
  10. static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
  11. static char[] TRIM_CHARS = { '\"' };
  12.  
  13. public static List<Dictionary<string, object>> Read(string file)
  14. {
  15. var list = new List<Dictionary<string, object>>();
  16. TextAsset data = Resources.Load(file) as TextAsset;
  17.  
  18. var lines = Regex.Split(data.text, LINE_SPLIT_RE);
  19.  
  20. if (lines.Length <= 1) return list;
  21.  
  22. var header = Regex.Split(lines[0], SPLIT_RE);
  23. for (var i = 1; i < lines.Length; i++)
  24. {
  25.  
  26. var values = Regex.Split(lines[i], SPLIT_RE);
  27. if (values.Length == 0 || values[0] == "") continue;
  28.  
  29. var entry = new Dictionary<string, object>();
  30. for (var j = 0; j < header.Length && j < values.Length; j++)
  31. {
  32. string value = values[j];
  33. value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
  34. object finalvalue = value;
  35. int n;
  36. float f;
  37. if (int.TryParse(value, out n))
  38. {
  39. finalvalue = n;
  40. }
  41. else if (float.TryParse(value, out f))
  42. {
  43. finalvalue = f;
  44. }
  45. entry[header[j]] = finalvalue;
  46. }
  47. list.Add(entry);
  48. }
  49. return list;
  50. }
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement