Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 多模式搜索-从文档中选择命中率最高的行_R_Regex - Fatal编程技术网

R 多模式搜索-从文档中选择命中率最高的行

R 多模式搜索-从文档中选择命中率最高的行,r,regex,R,Regex,我试图在句子列表中搜索术语或关键字列表。在这里,我想从行列表中选择这一行(这是来自客户的评论),这与我在中出现的大多数术语或关键字相匹配 现在我在做这个, mydata<-c("i like this product, awesome", "i could not go with this produt, since s/w is problem", "Very good s/w. keep up the good work. i really l

我试图在句子列表中搜索术语或关键字列表。在这里,我想从行列表中选择这一行(这是来自客户的评论),这与我在中出现的大多数术语或关键字相匹配

现在我在做这个,

mydata<-c("i like this product, awesome", 
          "i could not go with this produt, since s/w is problem",
          "Very good s/w. keep up the good work. i really like it")

terms<-c("really, "good", "like", "product")
termco(mydata, 1:3, terms)
我也尝试了一些其他的建议。但是我没有得到我想要的结果。但解决方案非常好

我的期望是,某一行或多行应该只显示具有我正在搜索的最大数量的术语或关键字

在这种情况下,我希望在下面一行,因为我有最大数量的术语或关键字,即“真的”、“好”和“喜欢”


提前感谢!!

这里有一个基本的R解决方案,使用
apply
grep
。基本思想是调用
grep(术语、句子)
,用于给定句子中的每个术语。然后,我们计算每个句子中命中术语的总数。请注意,我们在每个术语周围添加单词边界标记。这是为了防止一个术语恰好是句子中另一个单词的子字符串时出现错误匹配

sapply(mydata, function(x) {
    Reduce("+", sapply(terms, function(y) {
        sum(grep(paste0("\\b", y, "\\b"), x))
    }))
})

                          i like this product, awesome
                                                     2
i could not go with this product, since s/w is problem
                                                     1
Very good s/w. keep up the good work. i really like it
                                                     3

使用stringr的
stru计数也有帮助:

使用str_count获取所有匹配项的计数(最后一条记录总共4个),然后使用which.max获取向量的索引(在本例中,它将返回3,这意味着向量mydata的第三个元素)

如果希望与边界条件绝对匹配,可以使用:

mydata[which.max(stringr::str_count(mydata,paste0("\\b",paste0(terms, collapse="\\b|\\b"),"\\b")))]
在您的情况下,两个正则表达式都会给出相同的答案,但是第二个正则表达式会给出较少的匹配数。例如,当您在一个句子中有“keep”而不是“keep”这样的词时。在这种情况下,后面的正则表达式将不匹配,因为它不是绝对的,但是前面的正则表达式将匹配,因为没有设置边界条件

输出

> mydata[which.max(stringr::str_count(mydata, paste0(terms, collapse="|")))]
[1] "Very good s/w. keep up the good work. i really like it"

优秀的Tim..thx很多..你实际上给出了一个我没有放在问题陈述中的解决方案…事实上,我没有区分解决方案。这两个都是我的问题可以接受的。我选择第一个,因为它会带来额外的冲击count@AdarshaMurthy,请勾选绿色勾号以结束问题,接受任何一种解决方案hanksIn事实上,我并没有区分解决方案。我的问题可以接受这两种解决方案。我选择了第一种,因为它会提供额外的命中率。。。
mydata[which.max(stringr::str_count(mydata, paste0(terms, collapse="|")))]
mydata[which.max(stringr::str_count(mydata,paste0("\\b",paste0(terms, collapse="\\b|\\b"),"\\b")))]
> mydata[which.max(stringr::str_count(mydata, paste0(terms, collapse="|")))]
[1] "Very good s/w. keep up the good work. i really like it"