-
Notifications
You must be signed in to change notification settings - Fork 0
/
format-bibtex.py
72 lines (58 loc) · 2.16 KB
/
format-bibtex.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
#!/usr/bin/env python
"""
Format a bibtex file.
1. Organize alphabetically by ID.
2. Only include the following fields: author, year, title, journal,
volume, number, pages, doi.
Usage:
python format-bibtex.py file.bib
Note that it overwrites the original bibtex file, but only if the
script completes successfully. If the script fails due to an error,
the original file is unmodified and a temporary file of the same name
is available in /tmp. The last entry in this temporary file is the
last bibtex entry that was successfully formated.
"""
import os
import sys
import bibtexparser as bib
import shutil
bibtex_input = sys.argv[1]
assert os.path.isfile(bibtex_input), "bibtex file does not exist"
with open(bibtex_input) as bibtex_file:
bib_database = bib.load(bibtex_file)
bib_dict = bib_database.entries_dict
keys = bib_dict.keys()
keys = list(keys)
keys.sort()
bibtex_input_base = os.path.basename(bibtex_input)
bibtex_output = open("/tmp/" + bibtex_input_base, "w")
for k in keys:
entry = bib_dict[k]
entrytype = entry["ENTRYTYPE"]
out = "@%s{%s,\n"%(entrytype, entry["ID"])
if entrytype == "article":
for field in ["author", "year", "title", "journal", "volume", "number",
"pages"]:
if field not in entry.keys():
continue
out = out + "%s = {%s},\n"%(field, entry[field])
else:
fields_all = list(entry.keys())
fields_all.sort()
for field in fields_all:
if not field.islower():
continue
# bibtexparser converts the field "url" to "link", which is not
# recognized by the .bst file when formatting the references. This
# maintains the field as "url". Only applies to non-articles.
if field == "link":
entry["url"] = entry["link"]
field = "url"
out = out + "%s = {%s},\n"%(field, entry[field])
if "doi" in entry.keys():
out = out + "%s = {%s},\n"%("doi", entry["doi"])
out = out.rstrip(",\n") + "\n}\n"
bibtex_output.write(out)
bibtex_output.close()
# Overwrite original file
shutil.move("/tmp/" + bibtex_input_base, bibtex_input)