Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question
3  
Any code you are working on ? –  Sektor Feb 4 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 4 at 16:07

2 Answers 2

up vote 4 down vote accepted

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

share|improve this answer

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"]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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