reemplazar datos de una cadena en orden inverso

Luis Miguel Morillas morillas en gmail.com
Mar Feb 20 07:32:50 CET 2007


Utiliza un parser de XML (eso te exigirá que sea un documento bien
formado o procesarlo previamente para que lo sea)

>>> XML="<body><h2>subtitulo1</h2><p>parrafo</p><p>parrafo1</p><p>parrafo2</p><h2>subtitulo2</h2><p>parrafo3</p><h2>subtitulo3</h2></body>"
>>> import amara
>>> doc = amara.parse(XML)
>>> doc.body.h2[-1].nodeName = u'em'
>>> print doc.xml(indent=True)
<?xml version="1.0" encoding="UTF-8"?>
<body>
  <h2>subtitulo1</h2>
  <p>parrafo</p>
  <p>parrafo1</p>
  <p>parrafo2</p>
  <h2>subtitulo2</h2>
  <p>parrafo3</p>
  <em>subtitulo3</em>
</body>

Más info sobre amara: http://notes.4suite.org/AmaraXmlToolkit y
también algo en español aquí:
http://livingpyxml.python-hosting.com/wiki


El 20/02/07, Gabriel Genellina <gagsl-py en yahoo.com.ar> escribió:
> En Mon, 19 Feb 2007 23:34:13 -0300, Luis Rodrigo Gallardo Cruz
> <rodrigo en nul-unu.com> escribió:
>
> >> <h2>subtitulo1<h2><p>parrafo</p><p>parrafo1</p><p>parrafo2</p><h2>subtitulo2<h2><p>parrafo3</p><h2>subtitulo3<h2>
> >>
> >> quiero reemplazar el ultimo tag <h2> por <em>
> >>
> >> alguién sabe como puedo hacer esto fácilmente, he pensado en:
> >> 1. invertir la cadena
> >> 2. string.replace('<h2>','<em>',1)
> >> 3. string.replace('</h2>','</em>',1)
> >> 4. invertir nuevamente
> >
> > Pues, si *siempre* es el último, debería servir. Excepto que, por
> > supuesto, lo que necesitas reemplazar es '>2h<' por '>me<', e igual
> > con los '</>'.
>
> Otra forma sería buscar con rfind la posicion del ultimo <h2>, y hacer los
> reemplazos a partir de alli.
>
> ulth2 = texto.rfind('<h2>')
> if ulth2>=0:
>    texto = texto[:ulth2]
> + texto[ulth2:].replace('<h2>','<em>',1).replace('</h2>','</em>',1)
>
> Igual hay que tener cuidado, puede fallar muy facilmente si aparece algo
> como <H2> o < h2 > o <h2 class="subtitulo">
>
> --
> Gabriel Genellina
>
>
> _______________________________________________
> Python-es mailing list
> Python-es en aditel.org
> http://listas.aditel.org/listinfo/python-es
>
>


-- 
Saludos,

--

Luis Miguel




Más información sobre la lista de distribución Python-es