Read data file containing fractional numbers?



Hi list,

the really nice feature of the stream/stringproc variant is, that it 
parses strings and hence the file can contain algebraic expressions

Andre

On 05/20/2011 08:59 AM, Volker van Nek wrote:
> Hi Ted,
>
> you can use functions from stringproc:
>
> data.txt
>
> 1 0
> 2 -1/3
> 3 -1/2
> 4 -3/5
> 5 -2/3
>
>
> (%i1) stream: openr("data.txt");
> (%o1)       #<FD-STREAM for "file /home/volker/data.txt" {C6A00D1}>
> (%i2) display2d:false$
>
> (%i3) stringdisp:true$
>
> (%i4) lines:[]$
>
> (%i5) while (line: readline(stream)) # false do lines: endcons(line, lines)$
>
> (%i6) lines;
>
> (%o6) ["","1 0","2 -1/3","3 -1/2","4 -3/5","5 -2/3",""]
> (%i7) lines: delete("", lines);
>
> (%o7) ["1 0","2 -1/3","3 -1/2","4 -3/5","5 -2/3"]
> (%i8) strings: map(split, lines);
>
> (%o8) [["1","0"],["2","-1/3"],["3","-1/2"],["4","-3/5"],["5","-2/3"]]
> (%i9) numbers: fullmap(parse_string, strings);
>
> (%o9) [[1,0],[2,-1/3],[3,-1/2],[4,-3/5],[5,-2/3]]
> (%i10) 2*numbers;
>
> (%o10) [[2,0],[4,-2/3],[6,-1],[8,-6/5],[10,-4/3]]
> (%i11) close(stream);
>
> (%o11) true
>
> Some comments:
>
> Of course display2d:false and stringdisp:true are not necessary.
>
> The first and last line of the file was empty. Since parse_string cannot
> parse an empty string it is necessary to delete these empty strings from the
> list.
>
> The split function splits at blanks by default but other delimiters are also
> possible. See doc.
>
> Volker van Nek
>
>
> 2011/5/19 Edwin Woollett<woollett at charter.net>
>
>> Given a text data file with either
>> space or comma separated items which
>> may include signed fractional numbers,
>> such as:
>>
>> 1 0
>> 2 -1/3
>> 3 -1/2
>> 4 -3/5
>> 5 -2/3
>>
>> or
>>
>> 1,  0
>> 2,  -1/3
>> 3,  -1/2
>> 4,  -3/5
>> 5,  -2/3
>>
>> how can I use Maxima to read this data into a nested
>> list of the form
>> [ [1,0], [2,-1/3], [3, -1/2], [4, -3/5], [5, -2/3] ] .
>>
>> My attempts with read_nested_list result in things
>> like
>>
>> (%i22) fdataL : read_nested_list ("mydata2.dat",comma);
>> (%o22) [[1, 0], [2, [- 1, /, 3]], [3, [- 1, /, 2]], [4, [- 3, /, 5]],
>>                                                                 [5, [- 2, /,
>> 3]]]
>>
>> Ted Woollett
>>
>>
>> _______________________________________________
>> Maxima mailing list
>> Maxima at math.utexas.edu
>> http://www.math.utexas.edu/mailman/listinfo/maxima
>>
>
>
> _______________________________________________
> Maxima mailing list
> Maxima at math.utexas.edu
> http://www.math.utexas.edu/mailman/listinfo/maxima