]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/tools/special_phrases/sp_csv_loader.py
b7b24a7dff2cf3c70d148e5d97bfcc6e2d1a9b86
[nominatim.git] / nominatim / tools / special_phrases / sp_csv_loader.py
1 """
2     Module containing the SPCsvLoader class.
3
4     The class allows to load phrases from a csv file.
5 """
6 import csv
7 import os
8 from collections.abc import Iterator
9 from nominatim.tools.special_phrases.special_phrase import SpecialPhrase
10 from nominatim.errors import UsageError
11
12 class SPCsvLoader(Iterator):
13     """
14         Handles loading of special phrases from external csv file.
15     """
16     def __init__(self, csv_path):
17         super().__init__()
18         self.csv_path = csv_path
19         self.has_been_read = False
20
21     def __next__(self):
22         if self.has_been_read:
23             raise StopIteration()
24
25         self.has_been_read = True
26         self.check_csv_validity()
27         return self.parse_csv()
28
29     def parse_csv(self):
30         """
31             Open and parse the given csv file.
32             Create the corresponding SpecialPhrases.
33         """
34         phrases = set()
35
36         with open(self.csv_path) as file:
37             reader = csv.DictReader(file, delimiter=',')
38             for row in reader:
39                 phrases.add(
40                     SpecialPhrase(row['phrase'], row['class'], row['type'], row['operator'])
41                 )
42         return phrases
43
44     def check_csv_validity(self):
45         """
46             Check that the csv file has the right extension.
47         """
48         _, extension = os.path.splitext(self.csv_path)
49
50         if extension != '.csv':
51             raise UsageError('The file {} is not a csv file.'.format(self.csv_path))