gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:19:16 25 4
gpt4 key购买 nike

我想计算引理 GO 的搭配,包括它的所有形式,例如 go , goes , gone , 等等。:

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 的字符串是字符串中的第一个单词,稍后在字符串中再次出现:
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com