Re: Import numerical data and split by pattern
- To: mathgroup at smc.vnet.net
- Subject: [mg94471] Re: Import numerical data and split by pattern
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Sun, 14 Dec 2008 07:38:22 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <ghtjl9$rfu$1@smc.vnet.net>
Gehricht at googlemail.com wrote: > I am asking this more out of curiosity, but is there a neat way to > accomplish the following task within Mathematica. > Suppose I have a file as follows > ## a b c > 1 1.0 > 2 2.0 > # d e f > 3 3.0 > 4 4.0 > ## c d e > 5 5.0 > 6 6.0 > .... > Now I want everything between ## and # in a separate list, i.a. list1= > {{1,1.0},{2,2.0}}, list2={{5,5.0},{6,6.0}}, etc. > How could I get this? Among many other ways, you could import the file in memory and then select whatever you want. (Note that you could also do the processing while reading the file thanks to functions such as Read and the like.) The code below is just a "proof of concept" to help you started: it is neither bullet proof to error such as bad file structure nor efficient in terms of computation time and memory allocation (and, arguably, the code is not aesthetically pleasant). In[1]:= imp = Import["myFile.dat"] {list1, list2} = Module[{sub = {}, res = {}, c}, For[n = 1; save = false, n <= Length[imp], n++, c = imp[[n, 1]]; If[c === "##", save = True]; If[NumericQ[c] && save === True, AppendTo[sub, imp[[n]]]]; If[c === "#", save = False; AppendTo[res, sub]; sub = {}]; ]; If[Length[sub] > 0, AppendTo[res, sub]]; res ] list1 list2 Out[1]= {{"##", "a", "b", "c"}, {1, 1.}, {2, 2.}, {"#", "d", "e", "f"}, {3, 3.}, {4, 4.}, {"##", "c", "d", "e"}, {5, 5.}, {6, 6.}} Out[2]= {{{1, 1.}, {2, 2.}}, {{5, 5.}, {6, 6.}}} Out[3]= {{1, 1.}, {2, 2.}} Out[4]= {{5, 5.}, {6, 6.}} Regards, -- Jean-Marc