summary refs log tree commit diff stats
path: root/examples/statcsv.nim
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2009-05-08 16:36:06 +0200
committerAndreas Rumpf <rumpf_a@web.de>2009-05-08 16:36:06 +0200
commitdb4f617afcd095db087dcb52e3ea603cca111da7 (patch)
treeeeffcc8fb523171dc394c136acf9b8006ec4138f /examples/statcsv.nim
parent08bc9ac03c49db7bfcdee82f46aadf95a324e015 (diff)
downloadNim-db4f617afcd095db087dcb52e3ea603cca111da7.tar.gz
version 0.7.8
Diffstat (limited to 'examples/statcsv.nim')
-rw-r--r--examples/statcsv.nim60
1 files changed, 60 insertions, 0 deletions
diff --git a/examples/statcsv.nim b/examples/statcsv.nim
new file mode 100644
index 000000000..9c1ebd113
--- /dev/null
+++ b/examples/statcsv.nim
@@ -0,0 +1,60 @@
+# Example program to show the parsecsv module
+# This program reads a CSV file and computes sum, mean, minimum, maximum and
+# the standard deviation of its columns.
+# The CSV file can have a header which is then used for the output.
+
+import os, streams, parsecsv, strutils, math
+
+if paramCount() < 1:
+  quit("Usage: sumcsv filename[.csv]")
+
+var filename = appendFileExt(ParamStr(1), "csv")
+var s = newFileStream(filename, fmRead)
+if s == nil: quit("cannot open the file " & filename)
+
+var
+  x: TCsvParser
+  header: seq[string]
+  res: seq[TRunningStat]
+open(x, s, filename, separator=';', skipInitialSpace = true)
+while readRow(x):
+  if processedRows(x) == 1:
+    newSeq(res, x.row.len) # allocate space for the result
+    if validIdentifier(x.row[0]):
+      # header line:
+      header = x.row
+    else:
+      newSeq(header, x.row.len)
+      for i in 0..x.row.len-1: header[i] = "Col " & $(i+1)
+  else:
+    # data line:
+    for i in 0..x.row.len-1: 
+      push(res[i], parseFloat(x.row[i]))
+x.close()
+
+# Write results:
+for i in 0..header.len-1:
+  stdout.write("\t")
+  stdout.write(header[i])
+stdout.write("\nSum")
+for i in 0..header.len-1:
+  stdout.write("\t")
+  stdout.write(res[i].sum)
+stdout.write("\nMean")
+for i in 0..header.len-1:
+  stdout.write("\t")
+  stdout.write(res[i].mean)
+stdout.write("\nMin")
+for i in 0..header.len-1:
+  stdout.write("\t")
+  stdout.write(res[i].min)
+stdout.write("\nMax")
+for i in 0..header.len-1:
+  stdout.write("\t")
+  stdout.write(res[i].max)
+stdout.write("\nStdDev")
+for i in 0..header.len-1:
+  stdout.write("\t")
+  stdout.write(res[i].standardDeviation)
+stdout.write("\n")
+