-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
48 lines (37 loc) · 1.1 KB
/
utils.py
File metadata and controls
48 lines (37 loc) · 1.1 KB
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
46
47
48
import csv
import json
import pandas as pd
import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCache
session = CacheControl(requests.session(), cache=FileCache(".cache"))
def get(url):
r = session.get(url)
r.raise_for_status()
return r.text
def get_csv_as_json(path_to_csv, cache=False):
if cache:
csv_str = get(path_to_csv)
csv_pd = pd.read_csv(StringIO(csv_str), sep=",")
else:
csv_pd = pd.read_csv(path_to_csv, sep=",")
return json.loads(csv_pd.to_json(orient="records"))
def make_index(data, key):
idx = {}
idx["with_key_missing"] = []
for row in data:
if key in row:
idx.setdefault(row[key], [])
idx[row[key]].append(row)
else:
idx["with_key_missing"].append(row)
return idx
def read_csv(filename, url=False):
d = []
if url:
rows = get(filename).splitlines()
d = [line for line in csv.DictReader(rows)]
else:
with open(filename, "r") as data:
d = [line for line in csv.DictReader(data)]
return d