source: products/quintagroup.seoptimizer/trunk/quintagroup/seoptimizer/util.py @ 3189

Last change on this file since 3189 was 3189, checked in by vmaksymiv, 13 years ago

added unescaping functionality

  • Property svn:eol-style set to native
File size: 1.8 KB
Line 
1from AccessControl import ClassSecurityInfo
2from htmlentitydefs import entitydefs
3import re
4
5try:
6    from App.class_init import InitializeClass
7    InitializeClass
8except ImportError:
9    from Globals import InitializeClass
10
11
12class SortedDict(dict):
13    """ A sorted dictionary.
14    """
15    security = ClassSecurityInfo()
16
17    security.declarePublic('items')
18
19    def items(self):
20        primary_metatags = self.pmt
21        lst = [(name, self[name]) for name in primary_metatags \
22                                  if name in self.keys()] + \
23              [(name, self[name]) for name in self.keys() \
24                                  if name not in primary_metatags]
25        return lst
26
27    security.declarePublic('__init__')
28
29    def __init__(self, *args, **kwargs):
30        super(SortedDict, self).__init__(*args, **kwargs)
31        self.pmt = []
32    security.declarePublic('__setitem__')
33
34    def __setitem__(self, i, y):
35        super(SortedDict, self).__setitem__(i, y)
36        if i not in self.pmt:
37            self.pmt.append(i)
38    security.declarePublic('pop')
39
40    def pop(self, k, *args, **kwargs):
41        super(SortedDict, self).pop(k, *args, **kwargs)
42        if k in self.pmt:
43            self.pmt.remove(k)
44
45try:
46    InitializeClass(SortedDict)
47except:
48    pass
49
50
51def _group_unescape(m):
52    if m.group("ent"):
53        try:
54            return entitydefs[m.group("ent")]
55        except KeyError:
56            return m.group(0)
57    if m.group("dec"):
58        return unichr(int(m.group("dec")))
59    if m.group("hex"):
60        return unichr(int(m.group("hex"), 16))
61
62expr = re.compile(r'&(?:(?P<ent>\w+?)|'\
63                   '#(?P<dec>\d{1,10})|'\
64                   '#x(?P<hex>[0-9a-fA-F]{1,8}));')
65
66
67def unescape(s):
68    result = expr.sub(_group_unescape, s)
69
70    if isinstance(s, unicode):
71        return result
72    else:
73        return unicode(result)
Note: See TracBrowser for help on using the repository browser.