我正在尝试从非结构化文本中提取子字符串。例如,假设一个国家名称向量:
countries <- c("United States", "Israel", "Canada")
如何传递这个字符值向量以从非结构化文本中提取精确匹配。
text.df <- data.frame(ID = c(1:5),
text = c("United States is a match", "Not a match", "Not a match",
"Israel is a match", "Canada is a match"))
在此示例中,所需的输出为:
ID text
1 United States
4 Israel
5 Canada
到目前为止,我一直在使用 gsub
来删除所有不匹配项,然后删除然后删除具有空值的行。我也一直在使用 stringr 包中的 str_extract
,但没有成功让正则表达式的参数正确。任何帮助将不胜感激!
最佳答案
1.字符串
我们可以首先使用“indx”(由折叠“国家”向量形成)作为“grep”中的模式来子集“text.df”,然后使用“str_extract”从“文本”中获取模式元素列,将其分配给子数据集的“文本”列(“text.df1”)
library(stringr)
indx <- paste(countries, collapse="|")
text.df1 <- text.df[grep(indx, text.df$text),]
text.df1$text <- str_extract(text.df1$text, indx)
text.df1
# ID text
#1 1 United States
#4 4 Israel
#5 5 Canada
<强>2。基础R
不使用任何外部包,我们可以删除'ind'以外的字符
text.df1$text <- unlist(regmatches(text.df1$text,
gregexpr(indx, text.df1$text)))
3.字符串i
我们还可以使用 stringi
stri_extract
library(stringi)
na.omit(within(text.df, text1<- stri_extract(text, regex=indx)))[-2]
# ID text1
#1 1 United States
#4 4 Israel
#5 5 Canada
关于regex - 从R中的向量中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196831/