Text processing/1: Difference between revisions

Content added Content deleted
(Updated to work with Nim 1.4: replaced [1..-1]" with "[1..^1]. Changed output formatting to use the more friendly "strformat". Done miscellaneous other changes.)
(Actually done the changes described in previous edit.)
Line 2,442: Line 2,442:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>import os, strutils, sequtils
<lang nim>import os, sequtils, strutils, strformat


var
var
nodata = 0
nodata = 0
nodataMax = -1
nodataMax = -1
nodataMaxLine:seq[string] = @[]
nodataMaxLine: seq[string]


totFile = 0.0
totFile = 0.0
Line 2,453: Line 2,453:


for filename in commandLineParams():
for filename in commandLineParams():
var f = open(filename)
for line in filename.lines:
for line in f.lines:
var
var
totLine = 0.0
totLine = 0.0
numLine = 0
numLine = 0
field = line.split()
data: seq[float]
date = field[0]
flags: seq[int]
data: seq[float] = @[]
flags: seq[int] = @[]


let fields = line.split()
for i, f in field[1 .. -1]:
let date = fields[0]
if i mod 2 == 0: data.add parseFloat(f)
else: flags.add parseInt(f)


for datum, flag in items(zip(data, flags)):
for i, field in fields[1..^1]:
if i mod 2 == 0: data.add parseFloat(field)
else: flags.add parseInt(field)

for datum, flag in zip(data, flags).items:
if flag < 1:
if flag < 1:
inc nodata
inc nodata
Line 2,483: Line 2,483:
numFile += numLine
numFile += numLine


echo "Line: $# Reject: $# Accept: $# LineTot: $# LineAvg: $#"
let average = if numLine > 0: totLine / float(numLine) else: 0.0
.format(date, data.len - numLine, numLine,
echo &"Line: {date} Reject: {data.len - numLine:2} Accept: {numLine:2} ",
formatFloat(totLine, precision = 0), formatFloat(
&"LineTot: {totLine:6.2f} LineAvg: {average:4.2f}"
(if numLine > 0: totLine / float(numLine) else: 0.0), precision = 0))


echo()
echo &"""File(s) = {commandLineParams().join(" ")}"""
echo &"Total = {totFile:.2f}"
echo &"Readings = {numFile}"
echo &"Average = {totFile / float(numFile):.2f}"
echo ""
echo ""
echo &"Maximum run(s) of {nodataMax} consecutive false readings ",
echo "File(s) = ", commandLineParams().join(" ")
&"""ends at line starting with date(s): {nodataMaxLine.join(" ")}."""</lang>
echo "Total = ", formatFloat(totFile, precision = 0)

echo "Readings = ", numFile
{{out}}
echo "Average = ", formatFloat(totFile / float(numFile), precision = 0)
echo ""
echo "Maximum run(s) of ", nodataMax, " consecutive false readings ends at line starting with date(s): ", nodataMaxLine.join(" ")</lang>
Output:
<pre>$ ./textproc1 readings.txt | tail
<pre>$ ./textproc1 readings.txt | tail
Line: 2004-12-29 Reject: 1 Accept: 23 LineTot: 56.30 LineAvg: 2.45
Line: 2004-12-29 Reject: 1 Accept: 23 LineTot: 56.30 LineAvg: 2.45