-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
117 lines (92 loc) · 2.69 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# -*- coding: utf-8 -*-
"""Helpers for extracting data from XML."""
from config import languages
from arguments import arguments
def extract_strings(container):
"""Extract text from the <str> tag for each language into a dict.
Args:
container: <names> or <descs> element
Returns:
dict of strings
"""
strings = { }
for string in container.getElementsByTagName("str"):
language = string.getAttribute("language")
country = (
f'_{string.getAttribute("country")}'
if string.hasAttribute("country")
and string.getAttribute("country")
else ""
)
strings[f"{language}{country}"] = get_node_text(
string.getElementsByTagName("text")[0]
)
# If localization is missing, use English variant
if "en" in strings:
for key in languages.keys():
if key not in strings:
strings[key] = strings["en"]
return format_strings(strings)
def format_strings(strings):
"""Convert result of extract_strings (dict) into HTML string.
Args:
strings: output of extract_strings (dict)
Returns:
HTML string
"""
if arguments['format'] == 'html':
return "\n".join(
[
f'<span class="language language-{key}">{strings[key]}</span>'
for key in languages.keys()
if key in strings
]
)
else:
return (
strings[arguments['language']]
if arguments['language'] in strings
else strings['en']
if 'en' in arguments
else ''
)
def get_node_text(node):
"""Gen innerText of an XML node.
Args:
node: HTML node
Returns:
Inner text
"""
for node in node.childNodes:
if node.nodeType == node.TEXT_NODE:
return node.data
def get_child(node, tag_name):
"""Analog of JS's node.getElementsByTagName(tag_name)[0].
Args:
node: parent node
tag_name: tag name
Returns:
Returns first matching child element
Raises:
IndexError if unable to find the node
"""
return [
child
for child in node.childNodes
if child.nodeType != child.TEXT_NODE
and child.tagName == tag_name
][0]
def find_node(nodes, attribute, value):
"""Search among nodes by attribute.
Args:
nodes: list of nodes
attribute: attribute name
value: attribute value
Returns:
First matched node
Raises:
IndexError if unable to find the node
"""
return [
node for node in nodes if node.getAttribute(attribute) == value
][0]