我有一個資料集(z),其中的字串很長z$txt。我還有一個incd需要識別的關鍵字字典( )。在列z$inc.terms中。我需要所有關鍵字(相同的關鍵字可能在同一個字串中重復 n 次,所以每次出現都需要這個)之前和之后的 5 個字符(例如,這樣我可以看到“在其背景關系中的關鍵字”)。
#CREATE "z" DATASET
z<-data.frame(matrix("",3,3))
names(z)<-c("row","txt","inc.terms")
z$row<-c(1,2,3)
z[1,2]<-"I like the sky when the sky is blu not when the sky is grey"
z[2,2]<-"I like the mountains when the sky is blu not when the mountains are cloudy"
z[3,2]<-"I like the sky when the sky is dark in the mountains"
incd<-c("sky","mountains") #inclusion dictionary
這是我設法實作的,但它只回傳第一個關鍵字,我需要每個關鍵字(實際上這也不起作用,不知道為什么,但它適用于我的原始資料,這更復雜和不能共享以保護資料)。
for(i in incd){
for(j in z$row){
z$inc.terms[z$row==j]<-paste(z$inc.term[z$row==j],paste(stringr::str_sub(stringr::str_split(z$txt[z$row==j],i,simplify=TRUE)[,1],-5,-1),i,stringr::str_sub(stringr::str_split(z$txt[z$row==j],i,simplify=TRUE)[,2],1,5)),sep=" /// ")
}
}
這是我一直在使用的,但它回傳每個單元格中每個關鍵字的第一次出現,而不是每個關鍵字。
我想要的結果z$inc.terms如下z$inc.terms:
z[1,3] " the sky when" /// " the sky is b" /// " the sky is g"
z[2,3] " the mountains when" /// " the sky is b" /// " the mountains are "
z[3,3] " the sky when" /// " the sky is d" /// " the mountains"
uj5u.com熱心網友回復:
regmatches如果您使用base R,您可以嘗試
transform(
z,
inc.terms = regmatches(
txt,
gregexpr(
sprintf(".{0,5}(%s).{0,5}", paste0(incd, collapse = "|")),
txt
)
)
)
這使
row
1 1
2 2
3 3
txt
1 I like the sky when the sky is blu not when the sky is grey
2 I like the mountains when the sky is blu not when the mountains are cloudy
3 I like the sky when the sky is dark in the mountains
inc.terms
1 the sky when, the sky is b, the sky is g
2 the mountains when, the sky is b, the mountains are
3 the sky when, the sky is d, the mountains
uj5u.com熱心網友回復:
這是一個整潔的解決方案:
library(dplyr)
library(stringr)
z<-data.frame(matrix("",3,3))
names(z)<-c("row","txt","inc.terms")
z$row<-c(1,2,3)
z[1,2]<-"I like the sky when the sky is blu not when the sky is grey"
z[2,2]<-"I like the mountains when the sky is blu not when the mountains are cloudy"
z[3,2]<-"I like the sky when the sky is dark in the mountains"
incd<-c("sky","mountains")
words <- paste(incd, collapse="|")
z <- z %>%
mutate(inc.terms = str_extract_all(z$txt, paste0(".{5}(", words, ").{5}")))
z
#> row
#> 1 1
#> 2 2
#> 3 3
#> txt
#> 1 I like the sky when the sky is blu not when the sky is grey
#> 2 I like the mountains when the sky is blu not when the mountains are cloudy
#> 3 I like the sky when the sky is dark in the mountains
#> inc.terms
#> 1 the sky when, the sky is b, the sky is g
#> 2 the mountains when, the sky is b, the mountains are
#> 3 the sky when, the sky is d
z$inc.terms
#> [[1]]
#> [1] " the sky when" " the sky is b" " the sky is g"
#>
#> [[2]]
#> [1] " the mountains when" " the sky is b" " the mountains are "
#>
#> [[3]]
#> [1] " the sky when" " the sky is d"
由reprex 包創建于 2022-05-06 (v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470737.html
