Package translate :: Package storage :: Package xml_extract :: Module misc
[hide private]
[frames] | no frames]

Source Code for Module translate.storage.xml_extract.misc

 1  #!/usr/bin/env python 
 2  # -*- coding: utf-8 -*- 
 3  # 
 4  # Copyright 2008 Zuza Software Foundation 
 5  # 
 6  # This file is part of the Translate Toolkit. 
 7  # 
 8  # This program is free software; you can redistribute it and/or modify 
 9  # it under the terms of the GNU General Public License as published by 
10  # the Free Software Foundation; either version 2 of the License, or 
11  # (at your option) any later version. 
12  # 
13  # This program is distributed in the hope that it will be useful, 
14  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
16  # GNU General Public License for more details. 
17  # 
18  # You should have received a copy of the GNU General Public License 
19  # along with this program; if not, see <http://www.gnu.org/licenses/>. 
20   
21  import re 
22   
23  from translate.misc.typecheck import accepts, Self, IsCallable, IsOneOf, Any 
24 25 @accepts(IsCallable(), Any(), Any(), IsCallable(), state=[Any()]) 26 -def reduce_tree(f, parent_unit_node, unit_node, get_children, *state):
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
49 -def compose_mappings(left, right):
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|[-])*)')
63 64 -def parse_tag(full_tag):
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