yufree 我试了一下你这个方法,在文档里标记文献如下: "Let me cite a paper[@10.1007/978-981-10-1503-8]." 然后将该文档读入你写的函数转换,但转换后的文档是空白的(可能是我有些地方没有弄明白)。不过我根据你的思路写了一个函数,同样是读入一个文件,然后把 doi 标记转换为数字引用,并将文献列表附在文末。
doiadd <- function(path) {
cat("\n", file = path, append = TRUE)
y <- readLines(path)
ns <- which(y == "---")[2] + 1
ne <- length(readLines(path))
mystring <- y[ns:ne]
doi <- unlist(stringr::str_extract_all(mystring, "\\[\\@\\b10\\.(\\d+\\.*)+[\\/](([^\\s\\.])+\\.*)+\\b\\]"))
n <- factor(doi,levels = unique(doi))
n <- as.integer(n)
x <- mystring
for (i in 1:length(unique(doi))){
temp <- rcrossref::cr_cn(dois = stringr::str_sub(doi[i], 3, -2), format = "text", style = "apa")
cat("[", i, "]", ": " , temp, " \n", file = path, sep = "", append = TRUE)
}
y <- readLines(path)
for (i in 1:length(doi)) {x <- suppressWarnings(gsub(doi[i], paste0('[', n[i], ']'), x, fixed = T))}
y[ns:ne] <- x
writeLines(y, path)
}
第一次写这样的函数,估计有很多犯傻的地方,见笑了。