]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/token_analysis/housenumbers.py
Merge pull request #2621 from lonvia/housenumber-analyzer
[nominatim.git] / nominatim / tokenizer / token_analysis / housenumbers.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Specialized processor for housenumbers. Analyses common housenumber patterns
9 and creates variants for them.
10 """
11 import re
12
13 from nominatim.tokenizer.token_analysis.generic_mutation import MutationVariantGenerator
14
15 RE_NON_DIGIT = re.compile('[^0-9]')
16 RE_DIGIT_ALPHA = re.compile(r'(\d)\s*([^\d\s␣])')
17 RE_ALPHA_DIGIT = re.compile(r'([^\s\d␣])\s*(\d)')
18 RE_NAMED_PART = re.compile(r'[a-z]{4}')
19
20 ### Configuration section
21
22 def configure(rules, normalization_rules): # pylint: disable=W0613
23     """ All behaviour is currently hard-coded.
24     """
25     return None
26
27 ### Analysis section
28
29 def create(normalizer, transliterator, config): # pylint: disable=W0613
30     """ Create a new token analysis instance for this module.
31     """
32     return HousenumberTokenAnalysis(normalizer, transliterator)
33
34
35 class HousenumberTokenAnalysis:
36     """ Detects common housenumber patterns and normalizes them.
37     """
38     def __init__(self, norm, trans):
39         self.norm = norm
40         self.trans = trans
41
42         self.mutator = MutationVariantGenerator('␣', (' ', ''))
43
44     def normalize(self, name):
45         """ Return the normalized form of the housenumber.
46         """
47         # shortcut for number-only numbers, which make up 90% of the data.
48         if RE_NON_DIGIT.search(name) is None:
49             return name
50
51         norm = self.trans.transliterate(self.norm.transliterate(name))
52         # If there is a significant non-numeric part, use as is.
53         if RE_NAMED_PART.search(norm) is None:
54             # Otherwise add optional spaces between digits and letters.
55             (norm_opt, cnt1) = RE_DIGIT_ALPHA.subn(r'\1␣\2', norm)
56             (norm_opt, cnt2) = RE_ALPHA_DIGIT.subn(r'\1␣\2', norm_opt)
57             # Avoid creating too many variants per number.
58             if cnt1 + cnt2 <= 4:
59                 return norm_opt
60
61         return norm
62
63     def get_variants_ascii(self, norm_name):
64         """ Compute the spelling variants for the given normalized housenumber.
65
66             Generates variants for optional spaces (marked with '␣').
67         """
68         return list(self.mutator.generate([norm_name]))