]> git.openstreetmap.org Git - nominatim.git/blob - src/nominatim_api/query_preprocessing/regex_replace.py
Update documentation, optimise regex_replace, add tests
[nominatim.git] / src / nominatim_api / query_preprocessing / regex_replace.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2025 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 This file replaces values based on pre-defined regex rules:
9 """
10 from typing import List
11 import re
12
13 from .config import QueryConfig
14 from .base import QueryProcessingFunc
15 from ..search.query import Phrase
16
17
18 class _GenericPreprocessing:
19
20     def __init__(self, config: QueryConfig) -> None:
21         self.config = config
22
23         match_patterns = self.config.get('replacements', 'Key not found')
24         self.compiled_patterns = [
25             (re.compile(item['pattern']), item['replace']) for item in match_patterns
26             ]
27
28     def split_phrase(self, phrase: Phrase) -> Phrase:
29         """
30         This function performs replacements on the given text using regex patterns.
31         """
32         for item in self.compiled_patterns:
33             phrase.text = item[0].sub(item[1], phrase.text)
34
35         return phrase
36
37     def __call__(self, phrases: List[Phrase]) -> List[Phrase]:
38         """Apply regex replacements to the given addresses.
39         """
40         result = [p for p in map(self.split_phrase, phrases) if p.text.strip()]
41         return result if result else []
42
43
44 def create(config: QueryConfig) -> QueryProcessingFunc:
45     """ Create a function for generic preprocessing.
46     """
47     return _GenericPreprocessing(config)