July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Luther Blissett
You have plain text that follows certain common conventions (e.g., paragraphs are separated by empty lines, text meant to be highlighted is marked up _like this_), and you need to mark it up automatically as XML.
Producing XML markup from data that is otherwise structured, including plain text that rigorously follows certain conventions, is really quite easy:
def markup(text, paragraph_tag='paragraph', inline_tags={'_':'highlight'}): # First we must escape special characters, which have special meaning in XML text = text.replace('&', "&")\ .replace('<', "<")\ .replace('"', """)\ .replace('>', ">") # paragraph markup; pass any false value as the paragraph_tag argument to disable if paragraph_tag: # Get list of lines, removing leading and trailing empty lines: lines = text.splitlines(1) while lines and lines[-1].isspace(): lines.pop( ) while lines and lines[0].isspace( ): lines.pop(0) # Insert paragraph tags on empty lines: marker = '</%s>\n\n<%s>' % (paragraph_tag, paragraph_tag) for i in range(len(lines)): if lines[i].isspace( ): lines[i] = marker # remove 'empty paragraphs': if i!=0 and lines[i-1] == marker: lines[i-1] = '' # Join text again lines.insert(0, '<%s>'%paragraph_tag) lines.append('</%s>\n'%paragraph_tag) text = ''.join(lines) # inline-tags markup; pass any false value as the inline_tags argument to disable if inline_tags: for ch, tag in inline_tags.items( ): pieces = text.split(ch) ...Read now
Unlock full access