3

What am I not understanding?

The following code works fine:

from sympy.printing.mathml import print_mathml
s = "x**2 + 8*x + 16"
print_mathml(s)

But this generates an error:

from sympy.printing.mathml import mathml
s = "x**2 + 8*x + 16"
print mathml(s)

Ultimately, what I'm trying to do is get "x**2 + 8*x + 16" converted into presentation MathML for output on the web. So my plan was to use the mathml() function on the string, then send the output through c2p, such as the following:

from sympy.printing.mathml import mathml
from sympy.utilities.mathml import c2p
s = "x**2 + 8*x + 16"
print(c2p(mathml(s))

But as stated, the mathml() function throws up an error.

Fred Tyler
  • 31
  • 1
  • 2

2 Answers2

3

I do not have enough reputation points to comment yet, so i answer then instead.

According the Sympy doc's. Sympy.printing.mathml's mathml function is expecting a expression. But in string format?

http://docs.sympy.org/dev/modules/printing.html#sympy.printing.mathml.mathml

Code part:

def mathml(expr, **settings):
    """Returns the MathML representation of expr"""
    return MathMLPrinter(settings).doprint(expr)

-

def doprint(self, expr):
    """
    Prints the expression as MathML.
    """
    mathML = Printer._print(self, expr)
    unistr = mathML.toxml()
    xmlbstr = unistr.encode('ascii', 'xmlcharrefreplace')
    res = xmlbstr.decode()
    return res

Which error did you get?

Did you got this:

[....]
return MathMLPrinter(settings).doprint(expr)   File "C:\Python27\lib\site-packages\sympy\printing\mathml.py", line 39, in doprint
unistr = mathML.toxml() AttributeError: 'str' object has no attribute 'toxml'

I guess it's something wrong with the library.

unistr = mathML.toxml()

You could take a look here http://docs.sympy.org/dev/_modules/sympy/printing/mathml.html to see the file.

  • Thank you. Based on your response, I was able to dig up the 'sympify' function, which converts a string to an expression as follows: – Fred Tyler Dec 26 '14 at 18:55
3

As @Emyen notes, the problem is that your input is a string. Use sympify to convert the string to an expression, or, better yet, create the expression as a Python expression using symbols, like

x = symbols('x')
expr = x**2 + 8*x + 16

See https://github.com/sympy/sympy/wiki/Idioms-and-Antipatterns#strings-as-input for some reasons why using strings instead of expressions is a bad idea.

asmeurer
  • 86,894
  • 26
  • 169
  • 240