Last active
December 20, 2017 20:54
-
-
Save yestinj/de5fb0160df035ddb270fdc3db9f874c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys | |
def fix_mendeley_bib_file(infile, outfile): | |
total_processed = 0 | |
misc_changed = 0 | |
notes_added = 0 | |
with open(infile, "r") as b: | |
with open(outfile, "w+") as new: | |
for line in b: | |
total_processed += 1 | |
# If it's an entry of type misc, which Mendeley uses for webapges, | |
# replace it with @electronic which is a more suitable type. | |
if line.startswith("@misc"): | |
line = line.replace("@misc", "@electronic") | |
misc_changed += 1 | |
new.write(line) | |
continue | |
parts = line.split(' = ') | |
if len(parts) == 2: | |
if parts[0] == 'urldate': | |
date = parts[1] | |
date = date.rstrip() | |
note_line = "note = {Last accessed: %s}" | |
# If the last character is a , it means there is another element.. | |
if date[-1] == ',': | |
# Write out the oringal line first. | |
new.write(line) | |
# Now take '{yyyy-mm-dd},' date string into just yyyy-mm-dd | |
date = date[1:-2] | |
note_line = note_line % (date) | |
# Add the needed trailing comma | |
note_line += "," | |
else: | |
# If it doesn't end in a comma, need to add one to orig line. | |
# First remove the trailing newline and | |
updated_line = line.rstrip() | |
# Now write the original line, with a comman and newline added. | |
new.write(updated_line + ",\n") | |
date = date[1:-1] | |
note_line = note_line % (date) | |
# Write out the new line for the 'note' field. | |
new.write(note_line + '\n') | |
notes_added += 1 | |
else: | |
new.write(line) | |
else: | |
new.write(line) | |
print("Total lines processed %s" % total_processed) | |
print("Misc entries changed to electronic %s" % misc_changed) | |
print("Note fields added %s" % notes_added) | |
# If its run as a script, use the appropriate method. | |
if __name__ == "__main__": | |
if len(sys.argv) == 3: | |
print("Starting") | |
infile = sys.argv[1] | |
outfile = sys.argv[2] | |
fix_mendeley_bib_file(infile, outfile) | |
print("Done") | |
else: | |
print("Usage: %s <input_file> <output file>" % (sys.argv[0])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment