PHP计数出现2个单词列表出现字符串

时间:2015-10-13 04:56:36

标签: php

我有两个单词列表。这个想法是计算每个单词出现在文章中的次数,然后计算差异。

示例:

List1 = "how, now, brown, cow"
List2 = "he, usually, urges, an, umbrella, upon, us"
  

内容:“当雨伞更便宜时,我该怎么买牛?”

结果:List1(2) - List2(1) = 1

我有相当高贵的PHP技能。

1 个答案:

答案 0 :(得分:0)

在这种情况下,我们可以使用Php函数explodeincognito-skull提到的in_array。你可以这样做:

$list1 = ['how', 'now', 'brown', 'cow'];
$list2 = ['he', 'usually', 'urges', 'an', 'umbrella', 'upon', 'us'];

$timesAList1WordAppeared = 0;
$timesAList2WordAppeared = 0;

$text = "how can I buy a cow when the umbrella is cheaper?";
$wordArray = explode(' ', $text);

foreach ($wordArray as $word) {
    if (in_array($word, $list1)) {
        $timesAList1WordAppeared++;
    }

    if (in_array($word, $list2)) {
        $timesAList2WordAppeared++;
    }
}

echo "The difference is: ".($timesAList1WordAppeared - $timesAList2WordAppeared);

让我们一步一步走吧

首先,我们初始化数组和计数器变量

$list1 = ['how', 'now', 'brown', 'cow'];
$list2 = ['he', 'usually', 'urges', 'an', 'umbrella', 'upon', 'us'];

$timesAList1WordAppeared = 0;
$timesAList2WordAppeared = 0;

然后,我们初始化文本

$text = "how can I buy a cow when the umbrella is cheaper?";

然后,我们使用空格分割此文本以获取单词。这就是explode函数的用武之地,我们就像这样使用它

$wordArray = explode(' ', $text);

第一个参数是我们用来分割文本的字符或字符串,第二个参数是文本本身。然后,我们会仔细检查我们的list1list2中的单词出现在文本中的次数。我们这样做

foreach ($wordArray as $word) {
    if (in_array($word, $list1)) {
        $timesAList1WordAppeared++;
    }

    if (in_array($word, $list2)) {
        $timesAList2WordAppeared++;
    }
}

对于我们word中的每个wordArray,代码都是这样的,如果wordin_[the]_array list1,则递增timesAList1WordAppeared 。如果word也是in_[the]_array list2,请增加timesAList2WordAppeared

最后是打印结果

echo "The difference is: ".($timesAList1WordAppeared - $timesAList2WordAppeared);