PHP编程计算文件或数组中单词出现频率的方法

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP编程计算文件或数组中单词出现频率的方法。分享给大家供大家参考,具体如下:

如果是小文件,可以一次性读入到数组中,使用方便的数组计数函数进行词频统计(假设文件中内容都是空格隔开的单词):

<?php
$str = file_get_contents("/path/to/file.txt"); //get string from file
preg_match_all("/\b(\w+[-]\w+)|(\w+)\b/",$str,$r); //place words into array $r - this includes hyphenated words
$words = array_count_values(array_map("strtolower",$r[0])); //create new array - with case-insensitive count
arsort($words); //order from high to low
print_r($words)

如果是大文件,读入内存就不合适了,可以采用如下方法:

<?php
$filename = "/path/to/file.txt";
$handle = fopen($filename,"r");
if ($handle === false) {
 exit;
}
$word = "";
while (false !== ($letter = fgetc($handle))) {
 if ($letter == ' ') {
  $results[$word]++;
  $word = "";
 }
 else {
  $word .= $letter;
 }
}
fclose($handle);
print_r($results);

对于大文件,第二种方法比较快比较安全,不会引起内存异常。

PS:这里再为大家推荐2款非常方便的统计工具供大家参考使用:

在线字数统计工具:
http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php常用函数与技巧总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

ThinkPHP与PHPExcel冲突解决方法

很早之前就知道有一个叫做PHPExcel的类(官方网站)可以用来操作Excel,一直没有机会尝试,今天试用发现无比强大,下载后的源码包里有详细文档,几乎能实现手工操作Excel能实现的一...

PHP漏洞全解(详细介绍)

PHP漏洞全解(详细介绍)

针对PHP的网站主要存在下面几种攻击方式: 1、命令注入(Command Injection) 2、eval注入(Eval Injection) 3、客户端脚本攻击(Script In...

php计算年龄精准到年月日

本文实例讲述了php计算年龄精准到年月日的方法。分享给大家供大家参考。具体如下: <?php /* * To change this license header...

php HandlerSocket的使用

Memcache数据一致性的问题:当MySQL数据变化后,如果不能及时有效的清理掉过期的数据,就会造成数据不一致。这在强调即时性的Web2.0时代,不可取。 Memcache崩溃后的...

PHP 删除一个目录及目录下的所有文件的函数代码

复制代码 代码如下: /***** *@dir - Directory to destroy *@virtual[optional]- whether a virtual directo...