]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/special_phrases/sp_csv_loader.py
remove postcodes from countries that don't have them
[nominatim.git] / nominatim / tools / special_phrases / sp_csv_loader.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     Module containing the SPCsvLoader class.
9
10     The class allows to load phrases from a csv file.
11 """
12 import csv
13 import os
14 from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
15 from nominatim.errors import UsageError
16
17 class SPCsvLoader:
18     """
19         Handles loading of special phrases from external csv file.
20     """
21     def __init__(self, csv_path):
22         super().__init__()
23         self.csv_path = csv_path
24
25
26     def generate_phrases(self):
27         """ Open and parse the given csv file.
28             Create the corresponding SpecialPhrases.
29         """
30         self._check_csv_validity()
31
32         with open(self.csv_path, encoding='utf-8') as fd:
33             reader = csv.DictReader(fd, delimiter=',')
34             for row in reader:
35                 yield SpecialPhrase(row['phrase'], row['class'], row['type'], row['operator'])
36
37
38     def _check_csv_validity(self):
39         """
40             Check that the csv file has the right extension.
41         """
42         _, extension = os.path.splitext(self.csv_path)
43
44         if extension != '.csv':
45             raise UsageError(f'The file {self.csv_path} is not a csv file.')