Skip to content

Instantly share code, notes, and snippets.

@kikofernandez
Last active November 26, 2020 13:21
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 kikofernandez/0ae2740ec8debbc26fde3df28cbe1a9c to your computer and use it in GitHub Desktop.
Save kikofernandez/0ae2740ec8debbc26fde3df28cbe1a9c to your computer and use it in GitHub Desktop.
Capitalise title
# Original by Daniel L. Greenwald
# http://dlgreenwald.weebly.com/blog/capitalizing-titles-in-bibtex
# Modified by Garrett Dash Nelson
import re
from titlecase import titlecase
def capitalise(x):
if x[0].isupper():
x = "{" + x[0] + "}" + x[1:]
return x
# Input and output files
my_file = 'References.bib'
new_file = 'ReferencesCapitalized.bib' # in case you don't want to overwrite
# Match title, Title, booktitle, Booktitle fields
pattern = re.compile(r'(\W*)(title|journal)\s*=\s*{(.*)},')
# Read in old file
with open(my_file, 'r') as fid:
lines = fid.readlines()
# Search for title strings and replace with titlecase
newlines = []
errors = []
for line in lines:
# Check if line contains title
match_obj = pattern.match(line)
if match_obj is not None:
# Need to "escape" any special chars to avoid misinterpreting them in the regular expression.
oldtitle = re.escape(match_obj.group(3))
# Apply titlecase to get the correct title.
newtitle = titlecase(match_obj.group(3))
# Replace and add to list
p_title = re.compile(oldtitle)
try:
# Map is a lazy operation in Python 3
result = map(capitalise, newtitle.split(" "))
# Force lazy evaluation with list(...)
newtitle = " ".join(list(result))
newline = p_title.sub(newtitle, line)
except Exception as e:
errors.append((e, newtitle))
finally:
newlines.append(newline)
else:
# if not title, add as is.
newlines.append(line)
# Print output to new file
with open (new_file, 'w') as fid:
fid.writelines(newlines)
if errors:
print("This is an exception, please check the following articles:")
for (e, title) in errors:
print(f"f{e} -- {title}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment