3
$\begingroup$

I have some problems converting data which I imported from a txt-file into proper Mathematica expressions. After importing my data looks like

sample = {"{3", "\"string1\"", 45, "\"string2\"", 8.32, " {2013", 8, 1, 0, 6, " 19}", "0.}"}

Now I would like to transform it into

converted = {3, "string1", 45, "string2", 8.32`, {2013, 8, 1, 0, 6, 19}, 0.}

I imported the file using Import[file.txt,"Data"]

$\endgroup$
2
  • 2
    $\begingroup$ If you provide a sample from file.txt we might be able to make Import do a part of the job for you. $\endgroup$
    – C. E.
    Feb 21, 2014 at 10:34
  • $\begingroup$ Try to import as "Package", not "Data" if you have a list written using Mathematica syntax. $\endgroup$
    – Szabolcs
    Feb 21, 2014 at 18:21

2 Answers 2

7
$\begingroup$

You can Map with this:

ToExpression[StringJoin @@ Riffle[ToString /@ sample, ","]]
{3, "string1", 45, "string2", 8.32`, {2013, 8, 1, 0, 6, 19}, 0.`} 
$\endgroup$
3
  • $\begingroup$ Thanks for the elegant solution, solved my problem entirely $\endgroup$
    – RMMA
    Feb 21, 2014 at 11:19
  • $\begingroup$ @Kuba, Nice solution, but I wander: If this oddly shaped "sample" was imported from a text file, Wouldn't probably be better to parse the data correctly in the first instance, instead of correcting it afterwards? $\endgroup$
    – rhermans
    Feb 21, 2014 at 14:38
  • $\begingroup$ @rhermans That's what Pickett and Szabolcs are suggesting, I agree but OP has not responded to the comments. $\endgroup$
    – Kuba
    Feb 21, 2014 at 21:56
4
$\begingroup$

Another solution without the use of Riffle :

ToExpression@StringReplace[ToString[sample], {"\\" -> "", "{{" -> "{", "}}" -> "}"}]
$\endgroup$
2
  • 1
    $\begingroup$ Congratulations on your fanatic badge :) (temporary message) $\endgroup$ Feb 25, 2014 at 17:28
  • 1
    $\begingroup$ Thank you!(permanent message):-P $\endgroup$
    – tchronis
    Feb 25, 2014 at 18:05

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.