首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从段落中寻找匹配词的最有效方法

从段落中寻找匹配词的最有效方法
EN

Stack Overflow用户
提问于 2015-06-19 08:39:00
回答 3查看 2.4K关注 0票数 0

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

“我想改变。想让它成为一个更好的生活场所。和平、爱与和谐。这就是生活的全部。我们可以让我们的世界成为一个美好的生活之地。”

我的关键词是

“世界”、“地球”、“地方”

每当我有匹配的时候,我都应该报告,我应该报告多少次。

产出应是:

“世界”2次,“地点”1次

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-06-19 13:25:22

正如@CasimiretHippolyte评论的那样,regex是更好的方法,因为可以使用字界。使用i 标志还可以进行进一步的无案例匹配。与返回值一起使用:

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

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

代码语言:javascript
复制
$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 place => 1 foo => 0)

使用报价来转义没有必要的单词,如果你知道的话,它们不包含任何特写。要在array_combine中使用内联匿名函数,需要PHP5.3。

票数 1
EN

Stack Overflow用户

发布于 2015-06-19 09:00:33

代码语言:javascript
复制
<?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);
?>
票数 1
EN

Stack Overflow用户

发布于 2015-06-19 08:48:49

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

代码语言:javascript
复制
<?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";
}
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30933670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档