from htmlentitydefs import entitydefs
import formatter, re, StringIO
htmltag = re.compile('<.*?>', re.S)
#########################################################################
# Convert html entity defs to xml #
#########################################################################
def html2xml(html):
chunks=re.split('&(\w+);',html)
for i in range(1,len(chunks),2):
if chunks[i] in ['amp', 'lt', 'gt', 'apos', 'quot']:
chunks[i] ='&' + chunks[i] +';'
elif chunks[i] in entitydefs:
chunks[i]=entitydefs[chunks[i]]
if len(chunks[i])==1: chunks[i]=''+str(ord(chunks[i]))+';'
else:
chunks[i]='?'
return str("".join(chunks))
#########################################################################
# Remove html from string #
#########################################################################
def dehtml(html):
s=StringIO.StringIO()
f=formatter.AbstractFormatter(formatter.DumbWriter(s))
f.add_flowing_data(html2xml(htmltag.sub('',html)))
s.seek(0)
return s.read()
#########################################################################
# Convert high bit characters to numeric equivalents #
#########################################################################
def xmlchars(text):
if not isinstance(text,unicode):
try:
text = text.decode('utf-8')
except:
text = text.decode('iso-8859-1')
text=re.compile(u"[\x00-\x08\x0B\x0C\x0E-\x1F\ud800-\udfff\ufffe-\uffff]"). \
sub(lambda c: u'�' %
hex(ord(c.group(0)))[2:].rjust(4,'0').upper(),text)
for i in range(len(text)-1,-1,-1):
if text[i] not in ('\r','\n') and not ord(text[i]) in range(32,128):
text = '%s%d;%s' % (text[:i], ord(text[i]), text[i+1:])
return text
#########################################################################
# Determine the author of a given item #
#########################################################################
def authorFor(body):
patterns = [
'(.*)\s
\s
\sPosted by (.*?)$',
'(.*)\s
\s
\sPosted by (.*?)$',
'(.*)\sPosted by (.*?)$',
'(.*)\sPosted by (.*?)$',
'(.*)
Trackback from (.*?)',
'(.*)
Trackback from (.*?)$',
'(.*)
Pingback from (.*?)$',
'(.*)\s
Excerpt from (.*?)$',
'(.*)\s
Emailed by (.*?)$',
'(.*)\sEmailed by (.*?)$',
'(.*)\s
Message from (.*?)$',
'(.*)\s
Message from (.*?)$',
'(.*)\sMessage from (.*?)$',
'(.*)\sMessage from (.*?)$'
]
match=None
for pattern in patterns: match=match or re.search(pattern,body)
if match: return match.groups()[1]
#########################################################################
# Determine the id for a given link #
#########################################################################
def idFor(link):
(id,ext)=link.split('.',1)
if ext.find('#')>=0: id+='-'+ext.split('#',1)[1][1:]
return id
#########################################################################
# Wrap content as appropriate #
#########################################################################
def content(html, tag="content"):
result=('<%s type="application/xhtml+xml" mode="xml">'
'