-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_writer.py
45 lines (40 loc) · 1.39 KB
/
csv_writer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import csv
from typing import Optional, IO, Any
from ad import Ad
class CsvWriter:
def __init__(self) -> None:
self.csvFile: Optional[IO[str]] = None
self.writer: Optional[csv.DictWriter[str]] = None
def __enter__(self) -> 'CsvWriter':
self.csvFile = open('cache/result.csv', 'w', newline='',
encoding='utf-8')
self.writer = csv.DictWriter(self.csvFile, fieldnames=[
'id',
'url',
'has_washer',
'metro station',
'metro distance',
'title',
'score',
'price',
'date'
])
self.writer.writeheader()
return self
def write_csv(self, ad: Ad) -> None:
if self.writer:
metro = ad.closest_metro()
self.writer.writerow({
'id': ad.get_id(),
'url': ad.get_url(),
'has_washer': 'yes' if ad.is_washer_mentioned() else 'no',
'metro station': metro.name,
'metro distance': metro.distance(),
'title': ad.get_title_components()[0],
'score': ad.get_score(),
'price': ad.get_price(),
'date': ad.get_posted_date()
})
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
if self.csvFile:
self.csvFile.close()