# Convert a text file into a matrix I have a file with a list of elements inside the square of a Quadratic field, i.e. QQ(sqrt)^2. The file looks like [[2 + sqrt,4 - 2*sqrt],[2,sqrt],...]. I want to import this file into a single matrix over the field, in the previous example F.<a> = QuadraticField(13). Currently, I read everything in as a string then convert to the matrix, but there must be an easier way to do this. I am somewhat new to python programming in general.

edit retag close merge delete

Sort by » oldest newest most voted

There is no direct way to do that. Nevertheless, you may use the command sage_eval to convert your string to a list of lists.

sage: my_string = '[[sqrt(2),sqrt(3)], [sqrt(5),sqrt(7)]]'
sage: matrix(sage_eval(my_string))
[sqrt(2) sqrt(3)]
[sqrt(5) sqrt(7)]

more

This does not seem to work with variable names, such as sage: my_string = '[[x, 3 - x],[x, 3+x]]' Is there a way to make sage_eval work with these variables?

Nevermind, I got it: sage_eval(my_string, locals={'x':x})

Alternatively, an uglier but safer method (preventing possible evaluation of malicious code),

my_string = '[[sqrt(2),sqrt(3)], [sqrt(5),sqrt(7)]]'
matrix(filter(None, [map(SR, filter(lambda s:not s.strip() == '', l)) for l in map(lambda x:x.split(','), my_string.replace('[', '').split(']'))]))


Replace SR with whatever ring/field you want to coerce the entries into.

more