I have a really big symbolic output from Python, and it contains Sin
and Cos
. Now I want to solve it using Mathematica, but the sin and cos are written like sin(x) cos(x)
. How can I get them like Sin[x] Cos[x]
using Mathematica?
2 Answers
If this is the only problem then:
ToExpression["sin(x) cos(x)", TraditionalForm]
Cos[x] Sin[x]
here is a less hacky solution, the assumption is that there are no notmatching ()
escaped in strings or something:
FixedPoint[
StringReplace[
h : LetterCharacter .. ~~ "(" ~~ Shortest[x__] ~~ ")" /;
StringCount[x, "("] == StringCount[x, ")"] :>
Capitalize[h] <> "[" <> x <> "]"
],
"sin(sin(y))+cos(zxc)"
]
"Sin[Sin[y]]+Cos[zxc]"
Now, you can ToExpression
if you want.
As george2079 noticed an operator form of StringReplace
is new in 10.4 so for older versions one may need to use StringReplace[#, pattern]&
instead of StringReplace[pattern]
.
Capitalize
is new in 10.1 so for older versions the replacement would be something like: StringReplacePart[#, ToUpperCase@StringTake[#, 1], {1, 1}] &
-
$\begingroup$ Very interesting. What would be a less trivial example? Or does it only cover the simple
(x)
→[x]
, etc. transformations? $\endgroup$ Commented Dec 5, 2016 at 20:42 -
1$\begingroup$ This is a hack that only works when the syntax is simple. But it is really convenient. I use this all the time to transfer expressions. String patterns can't deal with bracket matching in general. +1 $\endgroup$– SzabolcsCommented Dec 6, 2016 at 10:52
-
$\begingroup$ Seems good. But my first comment wasn't a criticism. $\endgroup$– SzabolcsCommented Dec 7, 2016 at 11:51
-
1$\begingroup$ note the operator form of
StringReplace
is new in 10.4 or so. Need to doStringReplace[#, h: .... ]&
for older versions. $\endgroup$ Commented Dec 7, 2016 at 17:54 -
$\begingroup$ @george2079 thanks, I've added two notes for older versions users. $\endgroup$– KubaCommented Dec 7, 2016 at 18:09
You could import it as a string then use
StringReplace[
string,
{
"sin("~~Shortest[x__]~~")" :> "Sin["<>x<>"]",
"cos("~~Shortest[x__]~~")" :> "Cos["<>x<>"]"
}
]
You would then use ToExpression
to turn it into code input.
-
1$\begingroup$ What about
"sin(sin(y))"
? This is why I prefer the TraditionalForm solution that Kuba showed, even though it is an ugly hack. You could replace all(
by[
, but that will replace grouping parens too. Regular expressions are not capable of dealing with recursive tasks like bracket matching. A proper solution would require a full-blown parser. The closest ready-made thing we have to that is TraditionalForm parsing. $\endgroup$– SzabolcsCommented Dec 6, 2016 at 10:54 -
$\begingroup$ Maybe use Anton's parser? github.com/antononcube/MathematicaForPrediction/blob/master/… $\endgroup$– SzabolcsCommented Dec 6, 2016 at 10:58
ReplaceAll
(ctrl+h). $\endgroup$