1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 import re
22
23 from translate.misc.typecheck import accepts, IsCallable, Any
28 """Enumerate a tree, applying f to in a pre-order fashion to each node.
29
30 parent_unit_node contains the parent of unit_node. For the root of the tree,
31 parent_unit_node == unit_node.
32
33 get_children is a single argument function applied to a unit_node to
34 get a list/iterator to its children.
35
36 state is used by f to modify state information relating to whatever f does
37 to the tree.
38 """
39
40 def as_tuple(x):
41 if isinstance(x, tuple):
42 return x
43 else:
44 return (x,)
45
46 state = f(parent_unit_node, unit_node, *state)
47 for child_unit_node in get_children(unit_node):
48 state = reduce_tree(f, unit_node, child_unit_node, get_children, *as_tuple(state))
49 return state
50
53 """Given two mappings left: A -> B and right: B -> C, create a
54 hash result_map: A -> C. Only values in left (i.e. things from B)
55 which have corresponding keys in right will have their keys mapped
56 to values in right. """
57 result_map = {}
58 for left_key, left_val in left.iteritems():
59 try:
60 result_map[left_key] = right[left_val]
61 except KeyError:
62 pass
63 return result_map
64
65 tag_pattern = re.compile('({(?P<namespace>(\w|[-:./])*)})?(?P<tag>(\w|[-])*)')
69 """
70 >>> parse_tag('{urn:oasis:names:tc:opendocument:xmlns:office:1.0}document-content')
71 ('urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'document-content')
72 """
73 match = tag_pattern.match(full_tag)
74 if match is not None:
75 return unicode(match.groupdict()['namespace']), unicode(match.groupdict()['tag'])
76 else:
77 raise Exception('Passed an invalid tag')
78