r - 如何用 NA 标记缺失的左手搭配

标签 r regex

我想计算引理 GO 的搭配,包括其所有形式,例如 gogoesgone 等:

go <- c("go after it", "here we go", "he went bust", "go get it go", "i 'm gon na go", "she 's going berserk")

引理形式存储在此向量中:

lemma_GO <- c("go", "goes", "going", "gone", "went", "gon na")

这个向量将它们变成交替模式:

pattern_GO <- paste0("\\b(", paste0(lemma_GO, collapse = "|"), ")\\b")

但是,当使用带有 str_extract_all 的模式来提取 GO 紧邻的左侧搭配时,提取会错过那些 GO 所在的字符串。 code> 是字符串中的第一个单词,稍后会在字符串中重复出现:

library(stringr)
str_extract_all(go, paste0("'?\\b[a-z']+\\b(?=\\s?", pattern_GO, ")"))
[[1]]
character(0)

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1] "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"

预期结果是这样的:

[[1]]
[1] NA

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1]  NA  "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"

如何修改提取以在没有左侧搭配的情况下也返回 NA

最佳答案

您可以在字符串或您的消费模式的开头添加替代匹配:

str_extract_all(go, paste0("('?\\b[a-z']+\\b|^)(?=\\s?", pattern_GO, ")"))

请参阅regex demo .

请参阅R demo :

go <- c("go after it", "here we go", "he went bust", "go get it go", "i 'm gon na go", "she 's going berserk")
lemma_GO <- c("go", "goes", "going", "gone", "went", "gon na")
pattern_GO <- paste0("\\b(", paste0(lemma_GO, collapse = "|"), ")\\b")
library(stringr)
str_extract_all(go, paste0("('?\\b[a-z']+\\b|^)(?=\\s?", pattern_GO, ")"))

输出:

[[1]]
[1] ""

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1] ""   "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"


Sukces #stdin #stdout 0.26s 42528KB
[1] "\\b(go|goes|going|gone|went|gon na)\\b"
[[1]]
[1] ""

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1] ""   "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"

如果您愿意,您可以使用以下方法将所有空项目变成 NA

res <- str_extract_all(go, paste0("('?\\b[a-z']+\\b|^)(?=\\s?", pattern_GO, ")"))
res <- lapply(res, function(x) ifelse(x=="", NA, x))

关于r - 如何用 NA 标记缺失的左手搭配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65566442/

相关文章:

regex - 我应该如何找到包含两个字符串的所有文件?

regex - 什么风格的正则表达式应该与 DBpedia/Virtuoso SPARQL 一起使用?

Javascript:将非表达式简化为捕获组的正则表达式

regex - 我在 GNU sed 中的前瞻正则表达式有什么问题?

python - 用于在 Python 中匹配 URL 的正则表达式

r - ggplot 和 geom_sf 以及错误 : length(rows) == 1 is not TRUE

c++ - 从 Vowpal Wabbit 中的内存读取数据?

r - 如何从不平衡数据框架创建一个新的平衡数据框架,确保随机选择记录?

r - 如何以图例结尾创建单个几何点的几何线图

r - 如何让dput删除多余的数据?