2 Generic processor for names that creates abbreviation variants.
4 from collections import defaultdict
7 from icu import Transliterator
12 def create(norm_rules, trans_rules, config):
13 """ Create a new token analysis instance for this module.
15 return GenericTokenAnalysis(norm_rules, trans_rules, config['variants'])
18 class GenericTokenAnalysis:
19 """ Collects the different transformation rules for normalisation of names
20 and provides the functions to apply the transformations.
23 def __init__(self, norm_rules, trans_rules, replacements):
24 self.normalizer = Transliterator.createFromRules("icu_normalization",
26 self.to_ascii = Transliterator.createFromRules("icu_to_ascii",
29 self.search = Transliterator.createFromRules("icu_search",
30 norm_rules + trans_rules)
32 # Intermediate reorder by source. Also compute required character set.
33 immediate = defaultdict(list)
35 for variant in replacements:
36 if variant.source[-1] == ' ' and variant.replacement[-1] == ' ':
37 replstr = variant.replacement[:-1]
39 replstr = variant.replacement
40 immediate[variant.source].append(replstr)
41 chars.update(variant.source)
43 self.replacements = datrie.Trie(''.join(chars))
44 for src, repllist in immediate.items():
45 self.replacements[src] = repllist
48 def get_normalized(self, name):
49 """ Normalize the given name, i.e. remove all elements not relevant
52 return self.normalizer.transliterate(name).strip()
54 def get_variants_ascii(self, norm_name):
55 """ Compute the spelling variants for the given normalized name
56 and transliterate the result.
58 baseform = '^ ' + norm_name + ' ^'
64 while pos < len(baseform):
65 full, repl = self.replacements.longest_prefix_item(baseform[pos:],
68 done = baseform[startpos:pos]
69 partials = [v + done + r
70 for v, r in itertools.product(partials, repl)
71 if not force_space or r.startswith(' ')]
72 if len(partials) > 128:
73 # If too many variants are produced, they are unlikely
74 # to be helpful. Only use the original term.
77 startpos = pos + len(full)
86 # No variants detected? Fast return.
88 trans_name = self.to_ascii.transliterate(norm_name).strip()
89 return [trans_name] if trans_name else []
91 return self._compute_result_set(partials, baseform[startpos:])
94 def _compute_result_set(self, partials, prefix):
97 for variant in partials:
98 vname = variant + prefix
99 trans_name = self.to_ascii.transliterate(vname[1:-1]).strip()
101 results.add(trans_name)
106 def get_search_normalized(self, name):
107 """ Return the normalized version of the name (including transliteration)
108 to be applied at search time.
110 return self.search.transliterate(' ' + name + ' ').strip()