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