]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/token_analysis/postcodes.py
Merge pull request #2757 from lonvia/filter-postcodes
[nominatim.git] / nominatim / tokenizer / token_analysis / postcodes.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 postcodes. Supports a 'lookup' variant of the
9 token, which produces variants with optional spaces.
10 """
11
12 from nominatim.tokenizer.token_analysis.generic_mutation import MutationVariantGenerator
13
14 ### Configuration section
15
16 def configure(rules, normalization_rules): # pylint: disable=W0613
17     """ All behaviour is currently hard-coded.
18     """
19     return None
20
21 ### Analysis section
22
23 def create(normalizer, transliterator, config): # pylint: disable=W0613
24     """ Create a new token analysis instance for this module.
25     """
26     return PostcodeTokenAnalysis(normalizer, transliterator)
27
28
29 class PostcodeTokenAnalysis:
30     """ Special normalization and variant generation for postcodes.
31
32         This analyser must not be used with anything but postcodes as
33         it follows some special rules: `normalize` doesn't necessarily
34         need to return a standard form as per normalization rules. It
35         needs to return the canonical form of the postcode that is also
36         used for output. `get_variants_ascii` then needs to ensure that
37         the generated variants once more follow the standard normalization
38         and transliteration, so that postcodes are correctly recognised by
39         the search algorithm.
40     """
41     def __init__(self, norm, trans):
42         self.norm = norm
43         self.trans = trans
44
45         self.mutator = MutationVariantGenerator(' ', (' ', ''))
46
47
48     def normalize(self, name):
49         """ Return the standard form of the postcode.
50         """
51         return name.strip().upper()
52
53
54     def get_variants_ascii(self, norm_name):
55         """ Compute the spelling variants for the given normalized postcode.
56
57             Takes the canonical form of the postcode, normalizes it using the
58             standard rules and then creates variants of the result where
59             all spaces are optional.
60         """
61         # Postcodes follow their own transliteration rules.
62         # Make sure at this point, that the terms are normalized in a way
63         # that they are searchable with the standard transliteration rules.
64         return [self.trans.transliterate(term) for term in
65                 self.mutator.generate([self.norm.transliterate(norm_name)]) if term]