Frage

I have a string like:

text = ' A <EM ID="5103" CATEG="ORGANIZACAO" TIPO="INSTITUICAO">Legião da Boa    Vontade</EM> comemora amanhã o <EM ID="5104" CATEG="VALOR" TIPO="CLASSIFICACAO">10º.</EM> aniversário da sua implantação em <EM ID="5105" CATEG="LOCAL" TIPO="HUMANO">Portugal</EM> com cerimónias de carácter religioso e de convívio -- disse ontem fonte da organização. '

if i use:

     re.sub('<[^>]*>', '', text)

i will have something like this

A Legião da Boa Vontade comemora amanhã o 10º. aniversário da sua implantação em Portugal com cerimónias de carácter religioso e de convívio -- disse ontem fonte da organização. '

but i want to keep the CATEGS .. like <CATEG= "ORGANIZACAO">

like:

A `<CATEG="ORGANIZACAO">`Legião da Boa Vontade comemora amanhã o `<CATEG="VALOR" >`10º. aniversário da sua implantação em <CATEG="LOCAL">Portugal com cerimónias de carácter religioso e de convívio -- disse ontem fonte da organização.

How can i do it?

War es hilfreich?

Lösung

Try this:

In [32]: text
Out[32]: u' A <EM ID="5103" CATEG="ORGANIZACAO" TIPO="INSTITUICAO">Legi\xe3o da Boa    Vontade</EM> comemora amanh\xe3 o <EM ID="5104" CATEG="VALOR" TIPO="CLASSIFICACAO">10\xba.</EM> anivers\xe1rio da sua implanta\xe7\xe3o em <EM ID="5105" CATEG="LOCAL" TIPO="HUMANO">Portugal</EM> com cerim\xf3nias de car\xe1cter religioso e de conv\xedvio -- disse ontem fonte da organiza\xe7\xe3o. '

In [33]: re.sub(r'<EM[^C]*(CATEG="[^"]+")[^>]*>', r'<\1>', text).replace(r'</EM>', '')
Out[33]: u' A <CATEG="ORGANIZACAO">Legi\xe3o da Boa    Vontade comemora amanh\xe3 o <CATEG="VALOR">10\xba. anivers\xe1rio da sua implanta\xe7\xe3o em <CATEG="LOCAL">Portugal com cerim\xf3nias de car\xe1cter religioso e de conv\xedvio -- disse ontem fonte da organiza\xe7\xe3o. '

The rexeg simplifies the start tags, while the replace removes the end tags.

It is a good habit to use raw strings for regexes, do avoid unintended changes in your regex.

Andere Tipps

(based on your comment that the valid markup can be preserved) If you wanted to leverage a library that is designed to parse and modify HTML this could work (based on this answer)

import BeautifulSoup

text = ' A <EM ID="5103" CATEG="ORGANIZACAO" TIPO="INSTITUICAO">Legião da Boa    Vontade</EM> comemora amanhã o <EM ID="5104" CATEG="VALOR" TIPO="CLASSIFICACAO">10º.</EM> aniversário da sua implantação em <EM ID="5105" CATEG="LOCAL" TIPO="HUMANO">Portugal</EM> com cerimónias de carácter religioso e de convívio -- disse ontem fonte da organização. '

""" Remove Specific """
REMOVE_ATTRIBUTES = ['id','tipo']
soup = BeautifulSoup.BeautifulSoup(text)
for tag in soup.recursiveChildGenerator():
    try:
        tag.attrs = [(key,value) for key,value in tag.attrs if key not in REMOVE_ATTRIBUTES]
    except AttributeError:
        # 'NavigableString' object has no attribute 'attrs'
        pass

print(soup.prettify())

""" Keep Specific """
KEEP_ATTRIBUTES = ['categ']
soup = BeautifulSoup.BeautifulSoup(text)
for tag in soup.recursiveChildGenerator():
    try:
        tag.attrs = [(key,value) for key,value in tag.attrs if key in KEEP_ATTRIBUTES]
    except AttributeError:
        # 'NavigableString' object has no attribute 'attrs'
        pass

print(soup.prettify())

You could also use ElementTree:

from xml.etree import cElementTree as ElementTree
tree = ElementTree.parse(file_name)
root = tree.getroot()

content = ""
for item in root.iter():
    if item.tag == 'CATEG':
        # Do stuff with item
        content += item.text
    else:
        content += item.text
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top