|
Pages: [1]
|
 |
|
Author
|
Topic: troubles with a simple parser (Read 354 times)
|
|
glennmlewis
|
Say I have this:
line: {1974-12-31,195.40,195.40,185.70,185.70,879}
tick-class: make object! [ date: 1-Jan-1900 open: 0.0 high: 0.0 low: 0.0 close: 0.0 volume: 0 ]
tick-dialect: [ date: to-date string! to "," open: to-decimal string! to "," high: to-decimal string! to "," low: to-decimal string! to "," close: to-decimal string! to "," volume: to-integer string! to end ]
but I try this: parse line tick-dialect and it gives me an error: ** Script Error: Invalid argument: ?function? ** Where: halt-view ** Near: parse line tick-dialect
Any ideas? Thanks! -- Glenn Lewis
|
|
|
|
|
Logged
|
|
|
|
|
Anton
|
Hi Glenn, here are two approaches which work:
; object with example values of correct types tick-class: make object! [ date: 1-Jan-1900 open: 0.0 high: 0.0 low: 0.0 close: 0.0 volume: 0 ]
line: {1974-12-31,195.40,195.40,185.70,185.70,879}
; Create an object to store the values from the line obj: make tick-class [] set obj none ; <- so we are sure when we don't populate properly
; Populate the object - Approach #1 (2-pass)
use [blk][
; Separate the line into strings (losing the commas ",") and store in a block blk: parse line "," ; Some magic to convert each value to the corresponding type in TICK-CLASS. forall blk [ blk/1: to (pick third tick-class 2 * index? blk) blk/1 ] ; Set each value in the object with each value in the block set obj blk ]
; Populate the object - Approach #2 (1-pass, probably faster)
use [fields n set-field][
fields: third tick-class n: 0 set-field: [(n: n + 2 set in obj fields/(n - 1) to fields/:n str)] parse line [ any [ copy str to "," set-field "," ] copy str to end set-field ] ]
probe obj
Regards,
Anton.
|
|
|
|
|
Logged
|
|
|
|
|
glennmlewis
|
Thanks, Anton! I don't think I ever would have come up with those myself. Next question... say I have a ticks.csv file with lots of lines like we just parsed, and I want a series of 'ticks'... do I just loop over each line with 'foreach' and append the result to a series? Thanks again! -- Glenn
|
|
|
|
|
Logged
|
|
|
|
|
Anton
|
I don't muck around with CSV files much, but if it's true that each line in the CSV file is separated by a newline character, then this should work:
tick-class: make object! [...]
ticks: copy [] foreach line read/lines %your-file.csv [
; Create an object to store the values from the line obj: make tick-class [] set obj none ; <- so we are sure when we don't populate properly ; <--- populate the object here (as shown previously) append ticks obj
]
; now you should have a block full of tick objects
foreach tick ticks [probe tick/date] ; show all the dates, for example
|
|
|
|
|
Logged
|
|
|
|
|
|
Pages: [1]
|
|
|
 |
News: 01-09-08 Alpha version of REBOL 3 has been released!
2311 Posts in 595 Topics by 4141 Members
Latest Member: wintervssummer
|