Last active
April 7, 2022 02:32
-
-
Save joelnitta/dc592dfb0e35de0b33f157abc9e93344 to your computer and use it in GitHub Desktop.
Fix "Jr." in a YAML reference file rendered with CSL
This file contains hidden or 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
library(yaml) | |
library(stringr) | |
# Names with "Jr." need to have this in the "suffix" field, or they won't get rendered properly | |
# Zotero apparently doesn't know about this, so fix them with this script. | |
# Read in a reference library in YAML format | |
# (e.g. exported from zotero) | |
refs_yaml <- read_yaml("main_library.yaml") | |
# The entire thing is a nested list of length 1, so | |
# extract the actual references for easier handling | |
refs <- refs_yaml[[1]] | |
# Loop through and fix "Jr." in either last or given name | |
for(i in seq_along(refs)) { | |
for(j in seq_along(refs[[i]]$author)) { | |
family_has_jr <- FALSE | |
given_has_jr <- FALSE | |
if( | |
!is.null(refs[[i]]$author[[j]]$family) & | |
!is.null(refs[[i]]$author[[j]]$given)) { | |
family_has_jr <- str_detect(refs[[i]]$author[[j]]$family, "Jr\\.") | |
given_has_jr <- str_detect(refs[[i]]$author[[j]]$given, "Jr\\.") | |
refs[[i]]$author[[j]]$family <- str_remove_all( | |
refs[[i]]$author[[j]]$family, "Jr\\.") |> | |
str_squish() | |
refs[[i]]$author[[j]]$given <- str_remove_all( | |
refs[[i]]$author[[j]]$given, "Jr\\.") |> | |
str_squish() | |
if(family_has_jr | given_has_jr) { | |
refs[[i]]$author[[j]]$suffix <- "Jr." | |
} | |
} | |
} | |
} | |
# Replace the fixed references | |
refs_yaml[[1]] <- refs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment