Domanda

Sto usando il Python ElementTree modulo di manipolare HTML. Voglio sottolineare alcune parole, e la mia soluzione attuale è:

for e in tree.getiterator():
    for attr in 'text', 'tail':
        words = (getattr(e, attr) or '').split()
        change = False
        for i, word in enumerate(words):
            word = clean_word.sub('', word)
            if word.lower() in glossary:
                change = True
                words[i] = word.replace(word, '<b>' + word + '</b>')
        if change:
            setattr(e, attr, ' '.join(words))

È possibile che esamina il testo di ogni elemento e sottolinea le parole importanti che trova. Tuttavia lo fa inserendo tag HTML negli attributi di testo, che è sfuggito durante il rendering in modo che ho bisogno di contrastare con:

html = etree.tostring(tree).replace('&gt;', '>').replace('&lt;', '<')

Questo mi mette a disagio quindi voglio farlo correttamente. Tuttavia per incorporare un nuovo elemento che avrei avuto bisogno di spostare tutto il 'testo' e 'coda' attributi in modo che il testo enfatizzato apparso nella stessa posizione. E questo sarebbe davvero difficile quando l'iterazione come sopra.

Qualche consiglio su come farlo correttamente sarebbe apprezzato. Sono sicuro che c'è qualcosa che ho perso nella API!

È stato utile?

Soluzione

È inoltre possibile utilizzare XSLT e XPath una funzione personalizzata per fare questo.

Visibile qui di seguito è un esempio. Ha bisogno di ancora un po 'di lavoro, ad esempio la pulizia spazi extra alla fine degli elementi e la gestione misto di testo, ma è un'altra idea.

dato questo input:


<html>
<head>
</head>
<body>
<p>here is some text to bold</p>
<p>and some more</p>
</body>
</html>

e glossario contiene le due parole: alcuni, grassetto

poi output di esempio è:


<?xml version="1.0"?>
<html>
<head/>
<body>
<p>here is <b>some</b> text to <b>bold</b> </p>
<p>and <b>some</b> more </p>
</body>
</html>

Ecco il codice, ho anche postato su http://bkc.pastebin.com/f545a8e1d


from lxml import etree

stylesheet = etree.XML("""
    <xsl:stylesheet version="1.0"
         xmlns:btest="uri:bolder"
         xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

        <xsl:template match="@*">
            <xsl:copy />
        </xsl:template>

        <xsl:template match="*">
            <xsl:element name="{name(.)}">
                <xsl:copy-of select="@*" />
                <xsl:apply-templates select="text()" />
                <xsl:apply-templates select="./*" />
            </xsl:element>
        </xsl:template>

        <xsl:template match="text()">
            <xsl:copy-of select="btest:bolder(.)/node()" />
        </xsl:template>         
     </xsl:stylesheet>
""")

glossary = ['some', 'bold']

def bolder(context, s):
    results = []
    r = None
    for word in s[0].split():
        if word in glossary:
            if r is not None:
                results.append(r)
            r = etree.Element('r')
            b = etree.SubElement(r, 'b')
            b.text = word
            b.tail = ' '
            results.append(r)
            r = None
        else:
            if r is None:
                r = etree.Element('r')
            r.text = '%s%s ' % (r.text or '', word)

        if r is not None:
            results.append(r)
    return results

def test():
    ns = etree.FunctionNamespace('uri:bolder') # register global namespace
    ns['bolder'] = bolder # define function in new global namespace
    transform = etree.XSLT(stylesheet)
    print str(transform(etree.XML("""<html><head></head><body><p>here is some text to bold</p><p>and some more</p></body></html>""")))

if __name__ == "__main__":
    test()


Altri suggerimenti

Anche se ElementTree è molto facile da usare per la maggior parte delle attività di elaborazione XML, è anche scomodo per il contenuto misto. Io suggerisco di usare DOM parser:

from xml.dom import minidom
import re

ws_split = re.compile(r'\s+', re.U).split

def processNode(parent):
    doc = parent.ownerDocument
    for node in parent.childNodes[:]:
        if node.nodeType==node.TEXT_NODE:
            words = ws_split(node.nodeValue)
            new_words = []
            changed = False
            for word in words:
                if word in glossary:
                    text = ' '.join(new_words+[''])
                    parent.insertBefore(doc.createTextNode(text), node)
                    b = doc.createElement('b')
                    b.appendChild(doc.createTextNode(word))
                    parent.insertBefore(b, node)
                    new_words = ['']
                    changed = True
                else:
                    new_words.append(word)
            if changed:
                text = ' '.join(new_words)
                print text
                parent.replaceChild(doc.createTextNode(text), node)
        else:
            processNode(node)

Inoltre ho usato regexp per separare le parole per evitare che si attacchino insieme:

>>> ' '.join(ws_split('a b '))
'a b '
>>> ' '.join('a b '.split())
'a b'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top