【问题标题】:PHP: list number of times a word was found?PHP:找到一个单词的列表次数?
【发布时间】:2011-04-06 14:29:54
【问题描述】:

我有一个自定义日志,大约 29MB 的用户数据,包括用户代理。我想解析它(基本上只是搜索)并找出其中出现了多少“Firefox”或“MSIE”,就像迷你日志解析器一样。

这就是我难住的地方。我得到的是explode()ing 换行符,并遍历数组,使用:

if stripos($line, 'Firefox') $ff++;" 

或者一些愚蠢的东西,但我意识到这会占用大量内存/使用大量功能。

列出出现次数的好方法是什么?

【问题讨论】:

  • 为什么不用日志解析器?其中许多允许您设置格式,

标签: php performance logging iteration


【解决方案1】:

您需要逐行读取文件以避免大量数据耗尽内存。

$count = array('Firefox' => 0, 'MSIE' => 0, 'Others' => 0);
$handle = fopen("yourfile", "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);

        // actual counting here:
        if (stripos($buffer, 'Firefox')) {
            $count['Firefox']++;
        } else if (stripos($buffer, 'MSIE')) {
            $count['MSIE']++;

        // this might be irrelevant if not all your lines contain user-agent
        // strings, but is here to show the idea
        } else {
            $count['Others']++; 
        }
    }
    fclose($handle);
}

print_r($count);

还取决于您的文件格式(未提供),您可能希望使用正则表达式或更精细的方法来计算出现次数,例如:

$count = array('Firefox' => 0, 'MSIE' => 0, 'Others' => 0);
$handle = fopen("yourfile", "r");

if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        $ua = get_user_agent($buffer);  
        $count[$ua]++;
    }
    fclose($handle);
}

print_r($count);

/* @param $line
 * @return string representing the user-agent
 *
 * strpos() works for the most part, but you can use something more 
 * accurate if you want
 */
function get_user_agent($line) {
    // implementation left as an exercise to the reader
}

【讨论】:

  • 格式只是“[ID] [IP] [UA] [DATE]”或多或少,所以我会输入尽可能多的UA类型,“其他”将毫无用处机器人。谢谢!
  • 我们应该开始在我们的答案中使用“X left as a exercise to the reader”更多:D
  • 你可以使用php.net/manual/en/function.sscanf.php来解析你的线路日志
  • 完美,这实际上是一个非常有用的练习,我非常感谢答案。接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多