Project

General

Profile

1
# XML "function" nodes that evaluate their contents to text
2

    
3
import xml_dom
4

    
5
def map_items(func, items):
6
    return [(name, func(value)) for name, value in items]
7

    
8
def range_(items):
9
    items = dict(map_items(float, items))
10
    return str(items['to'] - items['from'])
11

    
12
def avg(items):
13
    count = 0
14
    sum_ = 0.
15
    for name, value in map_items(float, items):
16
        count += 1
17
        sum_ += value
18
    return str(sum_/count)
19

    
20
def date(items):
21
    items = dict(items)
22
    return '-'.join([items['year'], items.get('month', '1'),
23
        items.get('day', '1')])
24

    
25
def name(items):
26
    items = dict(items)
27
    return ' '.join([items['first'], items['last']])
28

    
29
def namePart(items):
30
    items = dict(items)
31
    def to_parts(name): return items[name].split(' ')
32
    parts = []
33
    if 'first' in items: parts += to_parts('first')[:1]
34
    if 'last' in items: parts += to_parts('last')[-1:]
35
    if 'middle' in items: parts += to_parts('middle')[1:-1]
36
    return ' '.join(parts)
37

    
38
# Function names must start with _ to avoid collisions with real tags
39
# Function names must be lowercase because name_of() returns name lowercased
40
# Functions take arguments (doc, node)
41
funcs = {'_range': range_, '_avg': avg, '_date': date, '_name': name,
42
    '_namepart': namePart}
43

    
44
def process(doc, node=None):
45
    if node == None: node = doc.documentElement
46
    name = xml_dom.name_of(node)
47
    if name in funcs: xml_dom.replace_with_text(doc, node,
48
        funcs[name](xml_dom.NodeTextEntryIter(node)))
49
    else:
50
        for child in xml_dom.NodeElemIter(node): process(doc, child)
(9-9/10)