Skip to content

Instantly share code, notes, and snippets.

@troeger
Last active August 7, 2017 06:15
Show Gist options
  • Save troeger/87848e8485c8f009537a6e085ce16a15 to your computer and use it in GitHub Desktop.
Save troeger/87848e8485c8f009537a6e085ce16a15 to your computer and use it in GitHub Desktop.
Script for emulating the Zotero BetterBibtex stable citation key feature
#!/usr/bin/env python
'''
Script for emulating the BetterBibtex stable citation key feature.
(see https://github.com/retorquere/zotero-better-bibtex)
input.bib: A BibLatex export from a Zotero 5 library that has "Extra" field
entries for stable BibTex keys ("bibtex: <my_key>"). They end up in the
note field of the standard Zotero 5 export.
output.bib: A BibTex file where the citation keys from the Extra/note field are
the real citation keys.
'''
import sys,re
if len(sys.argv)!=3:
print("{0} <input.bib> <output.bib>".format(sys.argv[0]))
exit(1)
regex_start=re.compile('@.*{(.*),')
data=open(sys.argv[1])
# Phase 1: Determine old key to new key mapping
old_key=None
mapping={}
for line in data:
if line.startswith('@'):
old_key=re.findall(regex_start,line)[0]
elif '{bibtex:' in line:
try:
new_key=re.findall(r'.*{bibtex: *(.*)}',line)[0]
new_key=new_key.replace('\\','')
new_key=new_key.replace('{','')
new_key=new_key.replace('}','')
mapping[old_key]=new_key
except:
print("Broken entry: "+old_key)
finally:
entry_started=False
# Phase 2: Create new file, based on mapping
data.seek(0)
output=open(sys.argv[2],'w')
for line in data:
if line.startswith('@'):
old_key=re.findall(regex_start,line)[0]
if old_key in mapping:
line=line.replace(old_key, mapping[old_key])
else:
print("Not converted: "+old_key)
if "note = {bibtex:" not in line:
output.write(line)
output.close()
data.close()
@wilenius
Copy link

wilenius commented Aug 7, 2017

Thanks for this, works like a charm!

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