从段落中查找匹配单词的最有效方法


Most efficient way to find matching words from paragraph

我有一个段落,我必须解析不同的关键字。例如,段落:

"我想改变世界。想让它成为一个更好的居住地。和平、爱与和谐。这就是生活的全部。我们可以让我们的世界成为一个宜居的好地方"

我的关键词是

"世界"、"地球"、"地方"

每当我有比赛时,我都应该报告多少次。

输出应为:

"

世界"2次,"地点"1次

目前,我只是将段落字符串转换为字符数组,然后将每个关键字与所有数组内容进行匹配。这是在浪费我的资源。请指导我采取有效的方法。(我正在使用PHP)

正如@CasimiretHippolyte所评论的那样,正则表达式是更好的方法,因为可以使用单词边界。可以使用 i 标志进行进一步的无大小写匹配。与返回值一起使用preg_match_all:

返回

完整模式匹配项的数量(可能为零),如果发生错误,则返回 FALSE。

匹配一个单词的模式是:/'bword'b/i。生成一个数组,其中键是搜索$words中的单词值,值是映射的单词计数,preg_match_all返回:

$words = array("earth", "world", "place", "foo");
$str = "at Earth Hour the world-lights go out and make every place on the world dark";
$res = array_combine($words, array_map( function($w) USE (&$str) { return
       preg_match_all('/'b'.preg_quote($w,'/').''b/i', $str); }, $words));

print_r($res); eval.in 输出处进行测试,以:

数组 ( [地球] => 1 [世界] => 2 [地点] => 1 [foo] => 0 )

用于preg_quote转义不必要的单词,如果您知道,它们不包含任何特殊内容。对于array_combine内联匿名函数的使用,需要 PHP 5.3

<?php
    Function woohoo($terms, $para) {
     $result =""; 
     foreach ($terms as $keyword) {
        $cnt = substr_count($para, $keyword);
        if ($cnt) {
          $result .= $keyword. " found ".$cnt." times<br>";
        }
      }
      return $result;
    }
    $terms = array('world', 'earth', 'place');
    $para = "I want to make a change in the world. Want to make it a better place to live.";
    $r = woohoo($terms, $para);
    echo($r);
?>

我将使用preg_match_all() .下面是它在代码中的外观。实际函数返回找到的项目计数,但 $matches 数组将保存结果:

<?php
$string = "world";
$paragraph = "I want to make a change in the world. Want to make it a better place to live. Peace, Love and Harmony. It is all life is all about. We can make our world a good place to live";
if (preg_match_all($string, $paragraph, &$matches)) {
  echo 'world'.count($matches[0]) . "times";
}else {
  echo "match NOT found";
}
?>