Skip to content

Instantly share code, notes, and snippets.

@zimmerst
Last active Apr 29, 2021
Embed
What would you like to do?
used to shorten *bibtex* files; parses a bibtex library and replaces excessive number of authors with 'others', leading to the typical *et al* behavior. All credit goes to the creators of bibtexparser :)
# author: stephan zimmer
# license: GPL
# date: 2018-01-27
# comment: script to shorten long (automatic) bibliographies to shorter names.
# requirement: https://bibtexparser.readthedocs.io
# usage: python shortenAuthors.py <bibfile> <number of names>
from argparse import ArgumentParser
from bibtexparser import loads as bib_loads, dumps as bib_dumps
from bibtexparser.bwriter import BibTexWriter
def loadDB(bibfile, max_authors):
""" returns short author list """
with open(bibfile) as bibtex_file:
bibtex_str = bibtex_file.read()
db = bib_loads(bibtex_str)
for item in db.entries:
auth = item['author']
#print auth
auth_list = auth.split("and ")
if len(auth_list) >= max_authors:
all_auth = auth_list[0:max_authors]
all_auth.append('others')
item['author'] = "and ".join(all_auth)
#print item
return db
def main(args=None):
parser = ArgumentParser(usage="Usage: %(prog)s [options]", description="shortens authorlist by replacing excess authors with 'others'")
parser.add_argument("-n","--nauthors",type=int, help="max number of authors", dest='max_authors', default=5)
parser.add_argument("-o","--output",dest='output', help="name of output file, default will take input file and change to <file>-short.bib", default=None)
parser.add_argument("-i","--input",dest='input', help="name of input bib file", required=True)
opts = parser.parse_args(args)
if opts.output is None:
out = opts.input.replace(".bib","-short.bib")
else:
out = opts.output
db = loadDB(opts.input, opts.max_authors)
writer = BibTexWriter()
with open(out, 'w') as bibfile:
bibfile.write(bib_dumps(db, writer).encode("utf-8"))
print 'wrote %s'%out
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment