3
$\begingroup$

I am running

a = RunProcess[$SystemShell, "StandardOutput", "python2 fit.py"]

which returns

"[ 0.04044647 0.75243326 -0.42992283]\n[ 0.04163976 0.15076435 0.31245249]\n"

How to turn it into a Mathematica expression?

$\endgroup$
  • 1
    $\begingroup$ I assume you are looking for something more sophisticated than ToExpression[StringReplace[..., {"[ " -> "{{", "]\n[ " -> "},{", "]" -> "}}", " " -> ","}]], right? $\endgroup$ – AccidentalFourierTransform May 11 at 16:09
  • $\begingroup$ Well, I thought there is something more direct, some FromPythonExpression or so. $\endgroup$ – corey979 May 11 at 16:42
  • $\begingroup$ There is an export type"Python expression" $\endgroup$ – user5601 May 11 at 17:06
5
$\begingroup$

Python lists have to have commas in between the numbers. With that fixed, we can use ImportString on each line individually:

ImportString["[ 0.04044647, 0.75243326, -0.42992283]", "PythonExpression"]

{0.0404465, 0.752433, -0.429923}

$\endgroup$
  • 1
    $\begingroup$ Hm, looks I need to figure out why python is giving me an array without commas :/ $\endgroup$ – corey979 May 11 at 17:25
  • 3
    $\begingroup$ @corey979 I would guess that you are using NumPy or something that uses NumPy under the hood, where the string representation of the array gives you space delimited arrays when printed. You could convert the NumPy array to a python list using tolist() and lists should be printed as comma delimited. For example, print(a[0].tolist()). $\endgroup$ – Tim Laska May 12 at 0:15
  • $\begingroup$ @TimLaska Indeed. Thanks! $\endgroup$ – corey979 May 12 at 7:11
2
$\begingroup$

An inelegant but functional solution:

test = "[ 0.04044647 0.75243326 -0.42992283]\n[ 0.04163976 0.15076435 0.31245249]\n";

Select[ToExpression[StringSplit[test, {" ", "[", "]"}]], NumberQ]

{0.0404465, 0.752433, -0.429923, 0.0416398, 0.150764, 0.312452}

Or if the list should be divided by "\n" first:

ToExpression[StringSplit[StringSplit[test, "\n"], {" ", "[", "]"}]]

{{0.0404465, 0.752433, -0.429923}, {0.0416398, 0.150764, 0.312452}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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