-
Notifications
You must be signed in to change notification settings - Fork 1
/
hanzipy_decomposer.py
327 lines (259 loc) · 10.6 KB
/
hanzipy_decomposer.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# coding:utf-8
"""
This file is taken from hanzipy library. A bug is fixed in the function
'get_characters_with_component()' to ignore key error when searching for fitting
characters
"""
import csv
import json
import logging
import re
from pathlib import Path
import hanzipy
from hanzipy.exceptions import NotAHanziCharacter
logging.basicConfig(level=logging.DEBUG)
RADICAL_REGEX = r"[一丨丶⺀丿乙⺃乚⺄亅丷]"
CURRENT_DIR = BASE_DIR = Path(hanzipy.__file__).parent
class HanziDecomposer:
def __init__(self):
self.characters = {}
self.radicals = {}
self.characters_with_component = {}
self.noglyph = "No glyph available"
self.init_decomposition()
self.compile_all_components()
def init_decomposition(
self,
):
# Reading in cjk_decomp - Decomposition Database
decomp_filepath = "{}/data/cjk_decomp.txt".format(CURRENT_DIR)
with open(decomp_filepath, encoding="utf-8") as decomp_file:
lines = decomp_file.readlines()
for line in lines:
colonsplit = line.split(":")
character = colonsplit[0]
decomposition = colonsplit[1]
openbracket = decomposition.index("(")
closebracket = decomposition.index(")")
decomposition_type = decomposition[0:openbracket]
components = decomposition[openbracket + 1 : closebracket].split(
","
) # noqa
self.characters[character] = {
"decomposition_type": decomposition_type,
"components": components,
}
# Reading in radical list
radical_filepath = "{}/data/radical_with_meanings.json".format(CURRENT_DIR)
with open(radical_filepath, encoding="utf-8") as radicals_file:
self.radicals = json.load(radicals_file)
def compile_all_components(
self,
):
filepath = "{}/data/chinese_charfreq_simpl_trad.csv".format(CURRENT_DIR)
with open(filepath, encoding="utf-8") as freq_file:
csvreader = csv.reader(freq_file)
next(csvreader, None) # skip the headers
for row in csvreader:
character = row[1]
line_num = row[0]
decomposition = self.decompose(character)
for component in decomposition["once"]:
if component not in self.characters_with_component:
if component != self.noglyph:
self.characters_with_component.setdefault(component, [])
self.characters_with_component[component].append(character)
elif component != self.noglyph:
self.characters_with_component[component].append(character)
for component in decomposition["radical"]:
if component not in self.characters_with_component:
if component != self.noglyph and not re.search(
RADICAL_REGEX, component
):
self.characters_with_component.setdefault(
component,
[],
)
if self.is_unique(
self.characters_with_component[component],
character,
): # noqa
self.characters_with_component[component].append(
character
) # noqa
elif component != self.noglyph and not re.search(
RADICAL_REGEX, component
):
if self.is_unique(
self.characters_with_component[component],
character,
): # noqa
self.characters_with_component[component].append(
character
) # noqa
logging.info("Done compiling {} characters".format(int(line_num) - 1))
return self.characters_with_component
def is_unique(self, array_list, token):
unique = True
for item in array_list:
if item == token:
unique = False
return unique
def decompose_many(self, characterstring, decomposition_type=None):
characterstring = str(characterstring)
# Not Hanzi
if not re.search("[\u4e00-\u9fff]", characterstring):
raise NotAHanziCharacter(characterstring)
decomposed_components = {}
# remove spaces from input string
characterstring = characterstring.replace(r"/\s/g", "")
if not characterstring:
raise "Invalid input"
for idx, char in enumerate(characterstring):
one_character = characterstring[idx : idx + 1]
# don't decompose the same character more than once
if one_character in decomposed_components.keys():
continue
decomposed_components[one_character] = self.decompose(
one_character, decomposition_type
)
return decomposed_components
def decompose(self, character, decomposition_type=None):
"""
Type of decomp:
1 = Only 2 components,
2 = Radical,
3 = Graphical
"""
character = character.replace(r"/\s/g", "")
if self.is_messy(character):
logging.error(self.is_messy(character))
return "Invalid Input"
decomposed_char = {}
if not decomposition_type:
decomposed_char = {
"character": character,
"once": self.once_decomposition(character),
"radical": self.radical_decomposition(character),
"graphical": self.graphical_decomposition(character),
}
elif decomposition_type == 1:
decomposed_char = {
"character": character,
"components": self.once_decomposition(character),
}
elif decomposition_type == 2:
decomposed_char = {
"character": character,
"components": self.radical_decomposition(character),
}
elif decomposition_type == 3:
decomposed_char = {
"character": character,
"components": self.graphical_decomposition(character),
}
else:
return
string = json.dumps(decomposed_char)
jsonoutput = json.loads(string)
return jsonoutput
# Functions to help with Decomposition
def once_decomposition(self, character):
components = self.get_components(character)
return self.replace_numbers(components)
def radical_decomposition(self, character):
final_array = []
if self.is_radical(character):
final_array.append(character)
else:
components = self.get_components(character)
if len(components) == 2:
for j in range(2):
final_array.extend(self.radical_decomposition(components[j]))
else:
final_array.append(character)
return self.replace_numbers(final_array)
def graphical_decomposition(self, character):
final_array = []
components = self.get_components(character)
if len(components) == 2:
for j in range(2):
final_array.extend(self.graphical_decomposition(components[j]))
else:
if not character.isdigit():
final_array.append(character)
else:
final_array.extend(self.resolve_number(character))
return final_array
def replace_numbers(self, characters):
finalreview = []
for char in characters:
if not char.isdigit():
finalreview.append(char)
else:
finalreview.append("No glyph available")
return finalreview
def resolve_number(self, number):
numbers_cleared = []
components = self.get_components(number)
for component in components:
if not component.isdigit():
numbers_cleared.append(component)
else:
numbers_cleared.extend(self.resolve_number(component))
return numbers_cleared
def get_characters_with_component(self, component):
if component in self.radicals.keys():
components = self.find_same_meaning_radicals(component)
characters = []
for component in components:
try:
if self.characters_with_component[component]:
characters.extend(self.characters_with_component[component])
except KeyError:
pass
return characters
else:
if component in self.characters_with_component.keys():
return self.characters_with_component[component]
return
def find_same_meaning_radicals(self, radical):
same_radicals = []
meaning = self.radicals[radical]
for radical in self.radicals:
if radical in self.radicals:
if self.radicals[radical] == meaning:
same_radicals.append(radical)
return same_radicals
def is_radical(self, character):
is_rad = False
if self.radicals.get(character):
is_rad = True
return is_rad
def get_components(self, character):
if self.component_exists(character):
if self.characters[character]["decomposition_type"] == "c":
return character
else:
return self.characters[character]["components"]
else:
return character
def get_radical_meaning(self, radical):
if self.is_radical(radical):
return self.radicals[radical]
else:
return
def component_exists(self, component):
return component in self.characters
def is_messy(self, character):
# If no input is sent
if not character:
return True
# If it's not a Chinese character
return not self.get_components(character)
if __name__ == "__main__":
logging.info("Compiling Hanzi characters data...")
# Compile Components into an object array for easy lookup
hanzi = HanziDecomposer()
res = hanzi.decompose("是")
print(res)