从R中的文本字段中提取列表中的术语
我有一个关于字符串提取的问题 我的表格如下:从R中的文本字段中提取列表中的术语,r,string,text,extract,R,String,Text,Extract,我有一个关于字符串提取的问题 我的表格如下: Text Monday is windy and raining Tuesday is sunny Wednesday is snowing and cold 我还有一个列表,其中包括: windy raining sunny snowing cold 我想从表1中提取列表中的术语: 因此,结果如下: Text Terms1 Terms2 Terms3 Monday
Text
Monday is windy and raining
Tuesday is sunny
Wednesday is snowing and cold
我还有一个列表,其中包括:
windy
raining
sunny
snowing
cold
我想从表1中提取列表中的术语:
因此,结果如下:
Text Terms1 Terms2 Terms3
Monday is windy and raining windy raining
Tuesday is sunny sunny
Wednesday is snowing and cold snowing cold
有没有办法让我做到这一点
谢谢你给我一个词向量:
> words
[1] "windy" "raining" "sunny" "snowing" "cold"
以及具有文本列的数据框:
您可以轻松创建文本中每个单词的真/假值矩阵:
> sapply(words, function(w){grepl(w,data$text)})
windy raining sunny snowing cold
[1,] TRUE TRUE FALSE FALSE FALSE
[2,] FALSE FALSE TRUE FALSE FALSE
[3,] FALSE FALSE FALSE TRUE TRUE
如果需要,可以将其添加到数据框中:
> cbind(data, sapply(words, function(w){grepl(w,data$text)}))
text windy raining sunny snowing cold
1 Monday is windy and raining TRUE TRUE FALSE FALSE FALSE
2 Tuesday is sunny FALSE FALSE TRUE FALSE FALSE
3 Wednesday is snowing and cold FALSE FALSE FALSE TRUE TRUE
您所提供的输出看起来像是一个非常粗糙的数据结构,作为列表可能是正确的,但是除非您能够澄清我所提供的代码应该足以让您使用一些基本的R代码将其转换为您想要的任何形式。查看grep和friends的帮助,了解如何在文本中搜索字符串。您可以创建一个for循环,并使用if term%in%表来选择要附加的术语。但您需要决定如何将输出存储为包含文本的术语列表或插入表单元格的列表。通常情况下,您不希望在上面示例所示的表中有长度不同的行。将所有单词插入到单元格中的单个列表中会遇到此术语%in%表不适用于搜索文本中的字符串,除非您将文本拆分为单独单词的向量。。。
library(stringr)
library(stringi)
Text <- c("Monday is windy and raining","Tuesday is sunny","Wednesday is snowing and cold")
terms <- c("windy","raining","sunny","snowing","cold")
terms_regex <- paste(terms,collapse="|")
stri_list2matrix(sapply(Text,function(x,terms_regex) str_extract_all(x,terms_regex),terms_regex),byrow=TRUE)
library(stringr)
library(stringi)
Text <- c("Monday is windy and raining","Tuesday is sunny","Wednesday is snowing and cold")
terms <- c("windy","raining","sunny","snowing","cold")
terms_regex <- paste(terms,collapse="|")
stri_list2matrix(sapply(Text,function(x,terms_regex) str_extract_all(x,terms_regex),terms_regex),byrow=TRUE)