Utilizzando lxml per estrarre i dati in cui tutti gli elementi non sono noti in anticipo
Domanda
Ho alcuni file SGML che sono più o meno standardizzati. Tuttavia, ci possono essere i dati contenuti all'interno di un tag che non so esiste prima ho aperto il file e personalmente letto. Ad esempio, i file di avere indirizzi e in generale gli indirizzi hanno una strada, una città, uno stato, una zip e un telefono. Ogni elemento del indirizzo è indicato con un tag
<ADDRESS>
<STREET>One Main Street
<CITY>Gotham City
<ZIP>99999 0123
<PHONE>555-123-5467
</ADDRESS>
Ma, per esempio, ho scoperto che ci sono tag per Paese, Street1, STREET2. Ho più di 200K file da elaborare e voglio sapere se è possibile tirare fuori tutti gli elementi degli indirizzi, senza doversi preoccupare di conoscere l'esistenza di tag sconosciuti.
Quello che ho fatto finora è
h=fromstring(my_data_in_a_string)
for each in h.cssselect('mail_address'):
each.text_content()
, ma ciò che ottengo è problematico perché non riesco a identificare dove finisce elementi e inizia il successivo
One Main StreetGotham City99999 0123555-123-5467
Soluzione
Per ottenere tutti i tag, abbiamo iter attraverso il documento in questo modo:
Supponiamo che il vostro struttura XML è come questo:
<ADDRESS>
<STREET>One Main Street</STREET>
<CITY>Gotham City</CITY>
<ZIP>99999 0123</ZIP>
<PHONE>555-123-5467</PHONE>
</ADDRESS>
analizzarlo:
>>> from lxml import etree
>>> f = etree.parse('foo.xml') # path to XML file
>>> root = f.getroot() # get the root element
>>> for tags in root.iter(): # iter through the root element
... print tags.tag # print all the tags
...
ADDRESS
STREET
CITY
ZIP
PHONE
Ora si supponga che il XML ha i tag in più pure; tag non sono a conoscenza circa. Dal momento che stiamo scorrendo l'XML, il codice di cui sopra tornerà questi tag pure.
<ADDRESS>
<STREET>One Main Street</STREET>
<STREET1>One Second Street</STREET1>
<CITY>Gotham City</CITY>
<ZIP>99999 0123</ZIP>
<PHONE>555-123-5467</PHONE>
<COUNTRY>USA</COUNTRY>
</ADDRESS>
I rendimenti sopra di codice:
ADDRESS
STREET
STREET1
CITY
ZIP
PHONE
COUNTRY
Ora, se vogliamo ottenere il testo dei tag, la procedura è la stessa. Basta stampare tag.text in questo modo:
>>> for tags in root.iter():
... print tags.text
...
One Main Street
One Second Street
Gotham City
99999 0123
555-123-5467
USA