PHP:我想计算文本文件中特定数量单词的出现

时间:2018-09-22 18:49:22

标签: php

<?php
$count_array = array("if","world");
$file = fopen('Data.txt', "r");
while(!feof($file))
{
    $line = fgets($file);
    if(trim($line) == "")
    continue;
    $OBJ = json_decode($line);
    foreach($count_array as $word)
    {
      echo '<b>' . $word . ' occurance are ' . substr_count(strtolower($OBJ->user->text), $word) . " times.</b><br />";
    }
  }
?>

这是代码。它只是一直循环直到文件结束,因为foreach在while循环内,如果我放在外面,它只会检查它得到的第一行。

输出:

if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 1 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.
if occurance are 0 times.
world occurance are 0 times.

...(依此类推)

我想要这样:

if occurance are 47 times.
world occurance are 7 times.

2 个答案:

答案 0 :(得分:1)

如果将整个单词表放入一个数组,则可以使用

parentNode.leftNode

有关更多信息,请参见http://php.net/manual/en/function.array-count-values.php(或一行中阅读http://php.net/manual/en/function.str-word-count.php)。那么$counts = array_count_values($count_array) 就像

$counts

然后,您可以遍历该列表以检查单词是否在单词列表中,并像

那样适当地回显
Array
(
    [if] => 47
    [world] => 7
    [otherword] => 17
)

或更好

foreach($counts as $word => $number) {
    if (in_array($word, $count_array) {
        echo $word.'</b> occurrence is '.$number.' times.<br>';
    }
}

要解析该行并计算要使用http://php.net/manual/en/function.str-word-count.php而不是foreach($count_array as $word) { echo $word.'</b> occurrence is '.intval($counts[$word]).' times.<br>'; } 的单词数,因为explode(' ', $line);将返回explode(' ', 'word word.');(请注意,句点为包括在内,因为您只是在空格上爆炸了)而array(0 => 'word', 1 => 'word.')会返回str_word_count('word word.', 1)(便于遍历和计数)。

编辑,添加完整(未试用)代码:

array(0 => 'word', 1 => 'word')

答案 1 :(得分:1)

尝试一下:

<?php

$count_array = ["if" => 0,"world" => 0];

$file = fopen('Data.txt', "r");

while(!feof($file))
{
    $line = trim(fgets($file));

    $words = explode(" ", $line);

    foreach($words as $word) {
        if (array_key_exists($word, $count_array)) {
            $count_array[$word]++;
        }
    }
}

foreach ($count_array as $word => $number) {
    echo $word . " occurred " . $number . " times" . PHP_EOL;
}

示例Data.txt

asd lol rotflol if
world rotflol world
bubu hehe gnigni if if
if hehe if world

结果:

$ php script.php
if occurred 5 times
world occurred 3 times