forked from flinder/text_analysis_syllabus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse_bib.py
69 lines (56 loc) · 2.17 KB
/
parse_bib.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
import bibtexparser
from operator import itemgetter
# +++++++++++++
# CONFIG
# +++++++++++++
BIBFILE = 'bibliography.bib'
OUTFILE = 'syllabus.md'
# Open and parse the bib file
with open(BIBFILE) as bibfile:
bibliography = bibfile.read()
bib_database = bibtexparser.loads(bibliography)
# Sort into categories
items = {}
for entry in bib_database.entries:
try:
cat = entry['category']
except KeyError:
cat = 'no_category'
# Make category if doesn't exist
if cat not in items.keys():
items[cat] = []
# Append entry in relevant category
items[cat].append(entry)
def writeline(line):
line = line + '\n\n'
outfile.write(line)
# Write markdown
with open(OUTFILE, 'w+') as outfile:
# Insert title and initial comments
writeline('# Text Analysis Community Syllabus')
writeline('This is an automatically generated document please do not edit this document. If you want to add references insert the information into [`bibliography.bib`](bibliography.bib). See the [readme file](README.md) for details')
# Write table of contents
writeline('## Contents')
for cat in items.keys():
line = '[{}]({})'.format(cat, cat)
writeline(line)
for cat in sorted(items.keys()):
line = '## <a name="{}"></a> {}'.format(cat, cat)
writeline(line)
sorted_entries = sorted(items[cat], key=lambda k: k['author'])
for entry in sorted_entries:
if entry['ENTRYTYPE'] == 'book':
line = "{} ({}). *{}*.".format(entry['author'], entry['year'],
entry['title'])
else:
try:
journal = entry['journal']
except KeyError:
journal = entry['booktitle']
line = "{} ({}). *{}*. {}.".format(entry['author'],
entry['year'],
entry['title'],
journal)
if 'link' in entry.keys():
line = line + ' [Link]({})'.format(entry['link'])
writeline(line)