2014-07-15 12 views
5

Sto cercando di scrivere un file XML usando il codice seguente:Come esportare numpy ndarray in una variabile stringa?

def make_xml(a_numpy_array): 

    from lxml import etree as ET 

    root = ET.Element('intersections') 
    intersection = ET.SubElement(root, 'intersection') 
    trace = ET.SubElement(intersection, 'trace') 
    trace.text = a_numpy_array 

    print ET.tostring(root, pretty_print=True, xml_declaration=True, encoding = 'utf-8') 

.....

trace.text aspetta una stringa di input. Voglio mettere qui il file xml un array 2D memorizzato come un ndarray numerico. Ma non riesco a essere in grado di esportare i dati su una stringa. numpy.tostring mi dà il bytecode, cosa devo fare con quello? la soluzione che si presenta è quella di scrivere il file ndarray in un file di testo e quindi leggere il file di testo come una stringa, ma mi piacerebbe poter saltare la scrittura di un file di testo.

risposta

2

È possibile utilizzare np.savetxt per scrivere l'array su io.BytesIO() (anziché su un file).

import numpy as np 
from lxml import etree as ET 
import io 

root = ET.Element('intersections') 
intersection = ET.SubElement(root, 'intersection') 
trace = ET.SubElement(intersection, 'trace') 

x = np.arange(6).reshape((2,3)) 
s = io.BytesIO() 
np.savetxt(s, x) 
trace.text = s.getvalue() 

print(ET.tostring(root, pretty_print=True, xml_declaration=True, encoding = 'utf-8')) 

cede

<?xml version='1.0' encoding='utf-8'?> 
<intersections> 
    <intersection> 
    <trace>0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00 
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00 
</trace> 
    </intersection> 
</intersections> 

allora si potrebbe caricare i dati di nuovo in un array NumPy utilizzando np.loadtxt:

for trace in root.xpath('//trace'): 
    print(np.loadtxt(io.BytesIO(trace.text))) 

cede

[[ 0. 1. 2.] 
[ 3. 4. 5.]] 
Problemi correlati