-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.py
84 lines (66 loc) · 2.17 KB
/
db.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from __future__ import unicode_literals
import re
import codecs
from collections import defaultdict
# parses:
# [this the title](http://google.com)
# [this the title](http://google.com) [rec1, rec2]
ENTRY_RE = re.compile(r'\[([^\]]+)\]\(([^)]+)\)( \[([^\]]+)\])?')
template = '''
# syllabus
{}
'''
def parse_entry(entry):
"""parse an entry from raw string representation"""
title, link, _, recommenders = ENTRY_RE.match(entry).groups()
if recommenders is None:
recommenders = []
else:
recommenders = recommenders.split(', ')
return title, link, recommenders
def format_entry(link, title, recommenders):
"""format an entry to raw string representation"""
if recommenders:
return '[{title}]({link}) [{reccers}]'.format(
title=title,
link=link,
reccers=', '.join(recommenders))
else:
return '[{title}]({link})'.format(
title=title,
link=link)
def format_category(category, entries):
# sorry
formatted_entries = [
format_entry(link,
data['title'],
data['recommenders'])
for link, data in sorted(entries.items())]
entries ='- {}'.format('\n- '.join(formatted_entries))
return '## {category}\n{entries}'.format(
category=category,
entries=entries)
def load(filename):
with codecs.open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines()
data = defaultdict(dict)
current_category = ''
for line in lines:
line = line.strip()
if not line:
continue
elif line.startswith('##'):
current_category = line.strip('## ').title()
elif line.startswith('- '):
title, link, recommenders = parse_entry(line[2:])
data[current_category][link] = {
'title': title,
'recommenders': recommenders
}
return data
def save(data, filename):
body = '\n\n'.join([
format_category(name, entries)
for name, entries in sorted(data.items())])
with codecs.open(filename, 'w', encoding='utf-8') as db:
db.write(template.format(body).strip())