-
Notifications
You must be signed in to change notification settings - Fork 1
/
bibtex_import.py
81 lines (63 loc) · 2.33 KB
/
bibtex_import.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
"""
Script used for BibTeX file importing into database from terminal
Usage - bibtex_import.py -f /path/to/bibtex
Really not bulletproof but it'll do for now.
"""
from optparse import OptionParser
from web.models import Reference
def bibtex_import(f):
lines = f.readlines()
success_count = 0
i = 0
while i < len(lines):
if lines[i][0] == '@':
entry_begin = i
# let's pull the next line in incase of line breaks in the preamble
preamble = lines[i] + lines[i + 1] + lines[i + 2]
entry_id = preamble.partition('{')[2].partition(',')[0]
# sanity/debug: print the extracted entryID
# print entry_id
# now grab the remainder
remainder = ""
bracket_depth = 0
had_bracket = False
i = entry_begin
# traverse each line for brackets, keeping track of bracket depth
# terminate when bracket depth is zero again
while (not (had_bracket and bracket_depth == 0)) and i < len(lines):
line = lines[i]
c = 0
while c < len(line):
# skip escapes!
if line[c] == '\\':
c += 1
elif line[c] == '{':
had_bracket = True
bracket_depth += 1
elif line[c] == '}':
bracket_depth -= 1
c += 1
remainder += line
i = i + 1
# destroy ref if already existing
try:
existing = Reference.objects.get(entry_id=entry_id)
existing.delete()
except:
None
# save into DB through Model
Reference(entry_id=entry_id.decode('utf-8'), bibtex=remainder.decode('utf-8')).save()
success_count += 1
else:
i += 1
print "Imported " + str(success_count) + " BibTeX entries"
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="input filename", metavar="FILE")
(options, args) = parser.parse_args()
try:
f = open(options.filename)
except:
print "Couldn't open BibTeX file."
bibtex_import(f)