[英]R: Extracting Bigrams with Zero-Width Lookaheads
我想從句子中提取二元組,使用此處描述的正則表達式並將輸出存儲到引用原始列的新列中。
library(dplyr)
library(stringr)
library(splitstackshape)
df <- data.frame(a =c("apple orange plum"))
# Single Words - Successful
df %>%
# Base R
mutate(b = sapply(regmatches(a,gregexpr("\\w+\\b", a, perl = TRUE)),
paste, collapse=";")) %>%
# Duplicate with Stringr
mutate(c = sapply(str_extract_all(a,"\\w+\\b"),paste, collapse=";")) %>%
cSplit(., c(2,3), sep = ";", direction = "long")
最初,我認為問題似乎出在正則表達式引擎上,但stringr::str_extract_all
(ICU) 和base::regmatches
(PCRE) 都base::regmatches
。
# Bigrams - Fails
df %>%
# Base R
mutate(b = sapply(regmatches(a,gregexpr("(?=(\\b\\w+\\s+\\w+))", a, perl = TRUE)),
paste, collapse=";")) %>%
# Duplicate with Stringr
mutate(c = sapply(str_extract_all(a,"(?=(\\b\\w+\\s+\\w+))"),paste, collapse=";")) %>%
cSplit(., c(2,3), sep = ";", direction = "long")
因此,我猜測問題可能與在捕獲組周圍使用零寬度前瞻有關。 R 中是否有任何有效的正則表達式可以提取這些二元組?
正如@WiktorStribiżew 所建議的,在這里使用str_extract_all
幫助。 以下是如何將其應用於數據框中的多行。 讓
(df <- data.frame(a = c("one two three", "four five six")))
# a
# 1 one two three
# 2 four five six
那么我們可以做
df %>% rowwise() %>%
do(data.frame(., b = str_match_all(.$a, "(?=(\\b\\w+\\s+\\w+))")[[1]][, 2], stringsAsFactors = FALSE))
# Source: local data frame [4 x 2]
# Groups: <by row>
#
# A tibble: 4 x 2
# a b
# * <fct> <chr>
# 1 one two three one two
# 2 one two three two three
# 3 four five six four five
# 4 four five six five six
其中stringsAsFactors = FALSE
只是為了避免來自綁定行的警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.