问题描述
我喜欢 Rmarkdown 生成文档的简便性,并且我正在Bibtex(* .bib)文档中维护自己的库。 我正在使用these instructions引用文档( bibtexkey 以“ @”符号开头)。
我的问题是:是否可以扫描Rmarkdown文档(* .Rmd)并提取该文档中引用的bibtexkey列表? 这对于生成要附加到项目而不是所有ca的库的子集可能非常有用。我的图书馆中积累了6000份参考文献。
解决方法
您可以通过查找给定的字符串模式(即.Rmd
)来解析@
文档。
示例:
创建示例文件
Rmd_txt <- "Lorem ipsum dolor sit amet [@bibkey_a],consectetur adipisici elit [@bibkey_b],sed eiusmod tempor incidunt ut labore et dolore magna aliqua [@bibkey_c;@bibkey_d]."
writeLines(Rmd_txt,"rmdfile.Rmd")
读取文件:
Rmd <- readChar("rmdfile.Rmd",nchars=1e6)
使用RegExp查找所有以[@
开头和以]
结尾的字符串的情况
pattern <- "\\[@(.*?)\\]"
m <- regmatches(Rmd,gregexpr(pattern,Rmd))[[1]]
m
[1] "[@bibkey_a]" "[@bibkey_b]" "[@bibkey_c;@bibkey_d]"
最后,根据需要拆分并清理字符串
res <- unlist(strsplit(m,";"))
res<- gsub("\\[","",res)
res<- gsub("\\]",res)
res
[1] "@bibkey_a" "@bibkey_b" "@bibkey_c" "@bibkey_d"
,
在研究了几种选择之后,我从软件包str_extract()
中访问了函数stringr
。
在这里,我假设您有一个bibtex库,其中包含所有引用的参考文献(通常更多)。
由于bibtexkey样式的不同,我也将Oto Kaláb的示例与自己的示例结合在一起。
首先是Rmd文档。
rmd_text <- c("# Introduction","Lorem ipsum dolor sit amet [@bibkey_a],","sed eiusmod tempor incidunt ut labore et dolore magna aliqua [@bibkey_c;@bibkey_d].","According to @Noname2000,the world is round [@Ladybug1999;Ladybug2009].","This knowledge got lost [@Ladybug2009a].")
writeLines(rmd_text,"document.Rmd")
注释下一个代码块。最后,我们获得一个包含所有引用参考的向量,可以用unique()
对其进行压缩。
# Bibtexkeys from bib file
keys <- c("bibkey_a","bibkey_b","bibkey_c","bibkey_d","Noname2000","Ladybug1999","Ladybug2009","Ladybug2009a")
keys <- paste0("@",keys)
# Read document
document <- readLines("document.Rmd")
# Scan document line by line
cited_refs <- list()
for(i in 1:length(document)) {
cited_refs[[i]] <- str_extract(document[i],keys)
}
# Final output
cited_refs <- unlist(cited_refs)
cited_refs <- cited_refs[!is.na(cited_refs)]
summary(as.factor(cited_refs))
然后可以将生成的矢量聚合起来,以了解文本中出现的频率(我认为也对检测稀有引文有用)。我也在考虑在输出中提取“行号”。
,一个更简单的解决方案是使用功能bbt_detect_citations()
程序包rbbt
。
另请参阅this discussion