How do I import data formatted in C or Fortran into Wolfram Language?
There are a few ways to import data into Mathematica as a list of strings. So here is just one example using a string to simulate an input file :
stringlist = ReadList[ StringToStream[
" 1SOL HW1 2 -0.542 -0.399 -0.468 \n
43NA NA32678 1.224 -0.131 0.941 \n
1048ISO H8332635 -3.331 -1.372 3.843 "],
Record, RecordSeparators -> "\n"];
stringlist // InputForm
which returns the following
{" 1SOL HW1 2 -0.542 -0.399 -0.468 ",
" 43NA NA32678 1.224 -0.131 0.941 ",
" 1048ISO H8332635 -3.331 -1.372 3.843 "}
We can extract the data from each string using a list of positions
sposlist = (# + {1, 0}) & /@ Partition[Accumulate @
{0, 5, 5, 5, 5, 8, 8, 8}, 2, 1];
(* {{1, 5}, {6, 10}, {11, 15}, {16, 20}, {21, 28}, {29, 36}, {37, 44}} *)
and the function StringTake
:
rawdata = StringTake[ stringlist, sposlist];
rawdata // InputForm
with results:
{{{" 1", "SOL ", " HW1", " 2", " -0.542", " -0.399", " -0.468"}},
{{" 43", "NA ", " NA", "32678", " 1.224", " -0.131", " 0.941"}},
{{" 1048", "ISO ", " H83", "32635", " -3.331", " -1.372", " 3.843"}}
Now we postprocess the raw data to its proper format:
data = Join[{ToExpression@#[[1]]}, #[[2 ;; 3]], ToExpression@#[[4 ;; 7]]] & /@ rawdata;
data // InputForm
which returns
{{1, "SOL ", " HW1", 2, -0.542, -0.399, -0.468},
{43, "NA ", " NA", 32678, 1.224, -0.131, 0.941},
{1048, "ISO ", " H83", 32635, -3.331, -1.372, 3.843}}