3
$\begingroup$

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})$.

$\endgroup$
3
  • 3
    $\begingroup$ Any code you are working on ? $\endgroup$
    – Sektor
    Feb 4, 2014 at 15:55
  • 1
    $\begingroup$ 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. $\endgroup$
    – Szabolcs
    Feb 4, 2014 at 16:07
  • $\begingroup$ Related: (1737), (15051), (38952) $\endgroup$
    – Mr.Wizard
    Mar 4, 2015 at 19:37

2 Answers 2

4
$\begingroup$

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

$\endgroup$
3
$\begingroup$

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"]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.