要在Web of Science中进行高级搜索,我们可以使用如下查询:
TI = ("ecology" AND ("climate change" OR "biodiversity"))这意味着我们希望提取标题包含“生态”和(“气候变化”或“生物多样性”)的论文。相应的正则表达式将是(这里TI是标题的字符串向量):
library(stringr)
str_detect(TI,"ecology") & str_detect(TI,"climate change|biodiversity")有没有办法从WoS查询中获取正则表达式?
发布于 2021-09-13 12:26:28
1)首先,我们需要更准确地定义问题。我们假设WoS查询是一个字符串,其中包含AND、or、NOT、圆括号和可能由双引号括起来的小写或混合大小写的固定字符串(这排除了出现在双引号中的大写and或OR,除非它是较长字符串的一部分)。我们假设我们希望生成一个字符串,该字符串包含一个R语句,其中包含问题中所示的str_detect实例,但只要满足上述条件,就不必与所示的示例相同。
对于AND、OR和NOT,我们只需将它们替换为运算符&、|和& !。然后,我们将单词字符的每个实例替换为后面跟着空格,然后是单词字符,除了空格被替换为下划线之外。然后,我们用引号括起来的字符串替换任何没有引号的单词字符串,最后将下划线恢复为空格。
如果s是结果字符串,则可以使用eval(parse(text = s)[[1]])根据target对其进行计算。
wos2stmt不使用任何包,但由于使用了str_detect来保证与问题的一致性,生成的语句依赖于stringr。
wos2stmt <- function(TI, target = "target") {
TI |>
gsub(pattern = "\\bNOT\\b", replacement = "& !") |>
gsub(pattern = "\\bAND\\b", replacement = "&") |>
gsub(pattern = "\\bOR\\b", replacement = "|") |>
gsub(pattern = "(\\w) +(\\w)", replacement = "\\1_\\2") |>
gsub(pattern = '(?<!")\\b(\\w+)\\b(?!")', replacement = '"\\1"', perl = TRUE) |>
gsub(pattern = "_", replacement = " ") |>
gsub(pattern = '("[^"]+")', replacement = sprintf("str_detect(%s, \\1)", target)) |>
gsub(pattern = '"(\\w)', replacement = r"{"\\\\b\1}") |>
gsub(pattern = '(\\w)"', replacement = r"{\1\\\\b"}")
}
# test
TI <- '"ecology" AND ("climate change" OR "biodiversity")'
stmt <- wos2stmt(TI)给予:
cat(stmt, "\n")
## [1] "str_detect(target, \"ecology\") & (str_detect(target, \"climate change\") | str_detect(target, \"biodiversity\"))"2)问题似乎指的是用str_detect生成R语句,但主题指的是生成正则表达式。在后一种情况下,我们接受WoS查询并输出用于str_detect的正则表达式,如下所示。我没有对此进行过太多的测试,所以您需要这样做才能探索它的局限性。
请注意,与(1)不同的是,这解决了我们定义为不包括not和自动引用的原始问题(它们在问题中没有作为要求提到)。
wos2rx <- function(TI) {
TI |>
gsub(pat = ' *\\bOR\\b *', repl = '|') |>
gsub(pat = ' *\\bAND\\b *', repl = '') |>
gsub(pat = ' *"([^"]+)" *', repl = '(?=.*\\1)')
}
# test
library(stringr)
TI <- '("ecology" AND ("climate change" OR "biodiversity"))'
rx <- wos2rx(TI)
str_detect("biodiversity ecology", rx)
## [1] TRUE
str_detect("climate change biodiversity", rx)
## [1] FALSEhttps://stackoverflow.com/questions/69161313
复制相似问题