我有一个数据集(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[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"