Skip to content

Instantly share code, notes, and snippets.

@eldrin
Created January 4, 2019 23:23
Show Gist options
  • Save eldrin/d2d45fb0bd8e5cf0c6b6ebabc864e508 to your computer and use it in GitHub Desktop.
Save eldrin/d2d45fb0bd8e5cf0c6b6ebabc864e508 to your computer and use it in GitHub Desktop.
A simple tool to merge two .bib files when one file only contains books and the other file only contains articles
import os
import argparse
import bibtexparser
def read_bibtex(fn):
"""Load bib file
"""
with open(fn) as bibf:
db = bibtexparser.load(bibf)
return db
def dump_bibtex(bibtexdb, fn):
"""Save bib file
"""
with open(fn, 'w') as bibf:
bibtexparser.dump(bibtexdb, bibf)
def flatten(bib_articles, bib_books, move_books=True,
to_copy=['title', 'year', 'month', 'location', 'publisher']):
"""Flatten article bib and book bib to one complete bib file
"""
# init empty DB
bib_out = bibtexparser.bibdatabase.BibDatabase()
# copy artices entries
bib_out.entries = bib_articles.entries
# flatten out xrefs
for article in bib_out.entries:
if 'crossref' in article:
book = bib_books.entries_dict[article['crossref']]
for key in to_copy:
if key in book:
article[('booktitle' if key == 'title' else key)] = book[key]
del article['crossref']
# move books
for book in bib_books.entries:
if book['ENTRYTYPE'] == 'book':
bib_out.entries.append(book)
return bib_out
def main(bib_articles_fn, bib_books_fn, out_fn):
"""Main process
"""
bib_articles = read_bibtex(bib_articles_fn)
bib_books = read_bibtex(bib_books_fn)
result = flatten(bib_articles, bib_books)
dump_bibtex(result, out_fn)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("articles_bib", type=str, help='path to articles db (.bib)')
parser.add_argument("books_bib", type=str, help='path to books db (.bib)')
parser.add_argument("out_fn", type=str, default=os.path.join(os.getcwd(), 'out.bib'),
help="path to save flattened output (.bib)")
args = parser.parse_args()
main(args.articles_bib, args.books_bib, args.out_fn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment