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