Skip to content

Instantly share code, notes, and snippets.

@mlouielu
Last active July 28, 2019 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlouielu/cfaf8bc5d15fdbd9154a0dcd60e1ef48 to your computer and use it in GitHub Desktop.
Save mlouielu/cfaf8bc5d15fdbd9154a0dcd60e1ef48 to your computer and use it in GitHub Desktop.
BibTex Field Purify
# -*- coding: utf-8 -*-
#
# BibTeX Purify
#
# Description
# This script will purify the BibTex file's fields and *overwrite* it
#
# Usage
# $ ./purify.py filename [filenames...]
#
# Example
# $ ./purify.py example.bib
# $ ./purify.py example1.bib example2.bib
#
# LICENSE - MIT
# Copyright 2019 Louie Lu
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import sys
import bibtexparser
#
# 1) You can change the field you want to keep in each ENTRYTYPE
# 2) Any Field which is UPPERCASE will be remain (e.g. ID, ENTRYTYPE)
#
KEYS = {
'common': {'author', 'year', 'booktitle', 'journal', 'title'},
'inproceedings': {},
'article': {'volume', 'number', 'pages'},
'misc': {'url', 'urldate', 'howpublished'},
'book': {'publisher'}
}
def purify(filename):
with open(filename) as f:
parser = bibtexparser.bparser.BibTexParser(common_strings=True)
db = bibtexparser.load(f, parser=parser)
for e in db.entries:
typ = e['ENTRYTYPE']
for k in list(e.keys()):
if not k.isupper() and k not in KEYS['common'] and k not in KEYS[typ]:
del e[k]
with open(filename, 'w') as f:
f.write(bibtexparser.dumps(db))
def main(filenames):
for filename in filenames:
purify(filename)
if __name__ == '__main__':
main(sys.argv[1:])
@mlouielu
Copy link
Author

mlouielu commented Jul 28, 2019

Make sure you have install bibtexparser first

$ python -m pip install bibtexparser --user

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment