Project

General

Profile

1 86 aaronmk
# XML "function" nodes that evaluate their contents to text
2
3 111 aaronmk
import datetime
4
5 278 aaronmk
import ex
6 86 aaronmk
import xml_dom
7
8 278 aaronmk
class SyntaxException(ex.ExceptionWithCause): pass
9
10 86 aaronmk
def map_items(func, items):
11
    return [(name, func(value)) for name, value in items]
12
13 278 aaronmk
def conv_items(type_, items):
14
    try: return map_items(type_, items)
15
    except ValueError, e: raise SyntaxException(e)
16
17 113 aaronmk
def alt(items):
18
    items = list(items)
19
    items.sort()
20
    return items[0][1] # value of lowest-numbered item
21
22 86 aaronmk
def range_(items):
23 278 aaronmk
    items = dict(conv_items(float, items))
24 86 aaronmk
    return str(items['to'] - items['from'])
25
26
def avg(items):
27
    count = 0
28
    sum_ = 0.
29 278 aaronmk
    for name, value in conv_items(float, items):
30 86 aaronmk
        count += 1
31
        sum_ += value
32
    return str(sum_/count)
33
34
def date(items):
35
    items = dict(items)
36 278 aaronmk
    year = items['year']
37
    month = items.get('month', '1')
38
    day = items.get('day', '1')
39
    try:
40
        year = float(year)
41
        month = int(month)
42
        day = int(day)
43
    except ValueError, e: raise SyntaxException(e)
44
    date = (datetime.date(int(year), month, day) +
45
        datetime.timedelta(round((year % 1.)*365)))
46 111 aaronmk
    return date.strftime('%Y-%m-%d')
47 86 aaronmk
48 89 aaronmk
def name(items):
49
    items = dict(items)
50
    return ' '.join([items['first'], items['last']])
51
52 102 aaronmk
def namePart(items):
53
    items = dict(items)
54
    def to_parts(name): return items[name].split(' ')
55
    parts = []
56
    if 'first' in items: parts += to_parts('first')[:1]
57
    if 'last' in items: parts += to_parts('last')[-1:]
58
    if 'middle' in items: parts += to_parts('middle')[1:-1]
59
    return ' '.join(parts)
60
61 86 aaronmk
# Function names must start with _ to avoid collisions with real tags
62 144 aaronmk
# Functions take arguments (items)
63 113 aaronmk
funcs = {'_alt': alt, '_range': range_, '_avg': avg, '_date': date,
64 138 aaronmk
    '_name': name, '_namePart': namePart}
65 86 aaronmk
66 142 aaronmk
def process(node):
67 139 aaronmk
    name = node.tagName
68 142 aaronmk
    if name.startswith('_') and name in funcs: xml_dom.replace_with_text(node,
69
        funcs[name](xml_dom.NodeTextEntryIter(node)))
70 86 aaronmk
    else:
71 142 aaronmk
        for child in xml_dom.NodeElemIter(node): process(child)