]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tokenizer/sanitizers/helpers.py
Merge pull request #2588 from lonvia/housenumber-sanitizer
[nominatim.git] / nominatim / tokenizer / sanitizers / helpers.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 Helper functions for sanitizers.
9 """
10 import re
11
12 from nominatim.errors import UsageError
13
14 def create_split_regex(config, default=',;'):
15     """ Converts the 'delimiter' parameter in the configuration into a
16         compiled regular expression that can be used to split the names on the
17         delimiters. The regular expression makes sure that the resulting names
18         are stripped and that repeated delimiters
19         are ignored but it will still create empty fields on occasion. The
20         code needs to filter those.
21
22         The 'default' parameter defines the delimiter set to be used when
23         not explicitly configured.
24     """
25     delimiter_set = set(config.get('delimiters', default))
26     if not delimiter_set:
27         raise UsageError("Empty 'delimiter' parameter not allowed for sanitizer.")
28
29     return re.compile('\\s*[{}]+\\s*'.format(''.join('\\' + d for d in delimiter_set)))
30
31
32 def create_kind_filter(config, default=None):
33     """ Create a filter function for the name kind from the 'filter-kind'
34         config parameter. The filter functions takes a name item and returns
35         True when the item passes the filter.
36
37         If the parameter is empty, the filter lets all items pass. If the
38         paramter is a string, it is interpreted as a single regular expression
39         that must match the full kind string. If the parameter is a list then
40         any of the regular expressions in the list must match to pass.
41     """
42     filters = config.get('filter-kind', default)
43
44     if not filters:
45         return lambda _: True
46
47     if isinstance(filters, str):
48         regex = re.compile(filters)
49         return lambda name: regex.fullmatch(name.kind)
50
51     regexes = [re.compile(regex) for regex in filters]
52     return lambda name: any(regex.fullmatch(name.kind) for regex in regexes)