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, Self, IsCallable, IsOneOf, Any
27 """Enumerate a tree, applying f to in a pre-order fashion to each node.
28
29 parent_unit_node contains the parent of unit_node. For the root of the tree,
30 parent_unit_node == unit_node.
31
32 get_children is a single argument function applied to a unit_node to
33 get a list/iterator to its children.
34
35 state is used by f to modify state information relating to whatever f does
36 to the tree.
37 """
38 def as_tuple(x):
39 if isinstance(x, tuple):
40 return x
41 else:
42 return (x,)
43
44 state = f(parent_unit_node, unit_node, *state)
45 for child_unit_node in get_children(unit_node):
46 state = reduce_tree(f, unit_node, child_unit_node, get_children, *as_tuple(state))
47 return state
48
50 """Given two mappings left: A -> B and right: B -> C, create a
51 hash result_map: A -> C. Only values in left (i.e. things from B)
52 which have corresponding keys in right will have their keys mapped
53 to values in right. """
54 result_map = {}
55 for left_key, left_val in left.iteritems():
56 try:
57 result_map[left_key] = right[left_val]
58 except KeyError:
59 pass
60 return result_map
61
62 tag_pattern = re.compile('({(?P<namespace>(\w|[-:./])*)})?(?P<tag>(\w|[-])*)')
65 """
66 >>> parse_tag('{urn:oasis:names:tc:opendocument:xmlns:office:1.0}document-content')
67 ('urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'document-content')
68 """
69 match = tag_pattern.match(full_tag)
70 if match is not None:
71 return unicode(match.groupdict()['namespace']), unicode(match.groupdict()['tag'])
72 else:
73 raise Exception('Passed an invalid tag')
74