我知道很多人已經發布了一些與我相關的問題,但我找不到正確的解決方案。
我有很多句子,例如:“治療:我非常喜歡大象適應癥”
我想提取上面提供的示例中“治療:”和“指示”之間的所有單詞,是否是“我非常喜歡大象”。
當我使用我的代碼時,我總是會得到接下來的 3 個單詞。我究竟做錯了什么?
my_df <- c("Therapie: I like the elephants so much Indication")
exc <- sub(".*?\\bTherapie\\W (\\w (?:\\W \\w ){0,2}).*", "\\1", my_df, to = "documents")`, perl=TRUE)
uj5u.com熱心網友回復:
與str_match. \\s*允許修剪空白。
str <- "Therapie: I like the elephants so much Indication"
library(stringr)
str_match(str, "Therapie:\\s*(.*?)\\s*Indication")[, 2]
# [1] "I like the elephants so much"
自定義函式呢?
str_between <- function(str, w1, w2){
stringr::str_match(str, paste0(w1, "\\s*(.*?)\\s*", w2))[, 2]
}
str_between(str, "Therapie:", "Indication")
# [1] "I like the elephants so much"
uj5u.com熱心網友回復:
你可以做
my_df <- c("Therapie: I like the elephants so much Indication")
sub("^Therapie: (.*) Indication$", "\\1", my_df)
#> [1] "I like the elephants so much"
uj5u.com熱心網友回復:
帶有trimwsfrom的選項base R
trimws(str, whitespace = ".*:\\s |\\s Indication.*")
[1] "I like the elephants so much"
資料
str <- "Therapie: I like the elephants so much Indication"
uj5u.com熱心網友回復:
另一種使用方式strsplit:
str <- "Therapie: I like the elephants so much Indication"
!strsplit(str, " ")[[1]] %in% c("Therapie:", "Indication") -> x
paste0(strsplit(str, " ")[[1]][x], collapse = ' ')
#"I like the elephants so much"
uj5u.com熱心網友回復:
僅匹配的另一個選項:
str <- "Therapie: I like the elephants so much Indication"
regmatches(str, regexpr("\\bTherapie:\\h*\\K.*?(?=\\h*\\bIndication\\b)", str, perl=TRUE))
輸出
[1] "I like the elephants so much"
模式匹配:
\bTherapie:防止匹配部分單詞的單詞邊界,匹配單詞Therapie和:\h*\K匹配可選空格并清除到目前為止匹配的內容.*?盡量少匹配(?=\h*\bIndication\b)正向前瞻,斷言可選空格和Indication右邊的單詞
查看R 演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435679.html
