3

I would like to read non-standard-format data into Mathematica from a file. How can this be achieved? For example, how can I read the following text file of data into Mathematica:

(8.675e-11+3.881e-11j) (7.775e-11+3.815e-11j) (0.675e-11+3.385e-11j)
(2.675e-11+3.889e-11j) (7.075e-11+3.835e-11j) (3.675e-11+3.815e-11j)
(0.675e-11+3.886e-11j) (7.975e-11+3.875e-11j) (7.675e-11+3.885e-11j)
(1.675e-11+3.828e-11j) (7.275e-11+3.185e-11j) (1.675e-11+3.805e-11j)

To explain, the first entry should be entered as the complex number $8.675 \times 10^{-11} + i (3.881 \times 10^{-11})$.

P. Plowman
  • 133
  • 2
  • 3
    Any code you are working on ? – Sektor Feb 04 '14 at 15:55
  • 1
    I would look at StringCases and see if I can extract the data using string patterns of regular expressions. It won't be fast or suitable for huge files but it should be possible. As a start read in the data using Import[..., "List" or "Table" or "String"] then StringSplit, finally use StringCases to structure it and ToExpression to convert the pieces to numbers. – Szabolcs Feb 04 '14 at 16:07

2 Answers2

4

For large files using ReadList is the way to go. So if we assume the name of your file is "file.txt", then the following should be efficient:

StringReplace[#, {"e" -> "*^", "j" -> "I"}] & /@ 
      ReadList["file.txt", Word, WordSeparators -> {"(", ")", " "}, 
       RecordLists -> True] // ToExpression

Mathematica graphics

RunnyKine
  • 33,088
  • 3
  • 109
  • 176
3

Here's a way using StringReplace:

text = "(8.675e-11+3.881e-11j) (7.775e-11+3.815e-11j) (0.675e-11+3.385e-11j)
        (2.675e-11+3.889e-11j) (7.075e-11+3.835e-11j) (3.675e-11+3.815e-11j)
        (0.675e-11+3.886e-11j) (7.975e-11+3.875e-11j) (7.675e-11+3.885e-11j)
        (1.675e-11+3.828e-11j) (7.275e-11+3.185e-11j) (1.675e-11+3.805e-11j)"


ToExpression[
  StringReplace[#, {"e" -> "*^", "j" -> "I", "(" -> "", ")" -> ""}]] & /@
  ImportString[text, "Table"]
kale
  • 10,922
  • 1
  • 32
  • 69