statcsv.nim 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Example program to show the parsecsv module
  2. # This program reads a CSV file and computes sum, mean, minimum, maximum and
  3. # the standard deviation of its columns.
  4. # The CSV file can have a header which is then used for the output.
  5. import os, streams, parsecsv, strutils, math, stats
  6. if paramCount() < 1:
  7. quit("Usage: statcsv filename[.csv]")
  8. var filename = addFileExt(paramStr(1), "csv")
  9. var s = newFileStream(filename, fmRead)
  10. if s == nil: quit("cannot open the file " & filename)
  11. var
  12. x: CsvParser
  13. header: seq[string]
  14. res: seq[RunningStat]
  15. open(x, s, filename, separator=';', skipInitialSpace = true)
  16. while readRow(x):
  17. if processedRows(x) == 1:
  18. newSeq(res, x.row.len) # allocate space for the result
  19. if validIdentifier(x.row[0]):
  20. # header line:
  21. header = x.row
  22. else:
  23. newSeq(header, x.row.len)
  24. for i in 0..x.row.len-1: header[i] = "Col " & $(i+1)
  25. else:
  26. # data line:
  27. for i in 0..x.row.len-1:
  28. push(res[i], parseFloat(x.row[i]))
  29. x.close()
  30. # Write results:
  31. for i in 0..header.len-1:
  32. stdout.write("\t")
  33. stdout.write(header[i])
  34. stdout.write("\nSum")
  35. for i in 0..header.len-1:
  36. stdout.write("\t")
  37. stdout.write(res[i].sum)
  38. stdout.write("\nMean")
  39. for i in 0..header.len-1:
  40. stdout.write("\t")
  41. stdout.write(res[i].mean)
  42. stdout.write("\nMin")
  43. for i in 0..header.len-1:
  44. stdout.write("\t")
  45. stdout.write(res[i].min)
  46. stdout.write("\nMax")
  47. for i in 0..header.len-1:
  48. stdout.write("\t")
  49. stdout.write(res[i].max)
  50. stdout.write("\nStdDev")
  51. for i in 0..header.len-1:
  52. stdout.write("\t")
  53. stdout.write(res[i].standardDeviation)
  54. stdout.write("\n")