源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-08-18 10:41 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要: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);

对于大文件,第二种方法比较快比较安全,不会引起内存异常。 [b]PS:这里再为大家推荐2款非常方便的统计工具供大家参考使用:[/b] [b]在线字数统计工具: [/b][url=http://tools.jb51.net/code/zishutongji]http://tools.jb51.net/code/zishutongji[/url] [b]在线字符统计与编辑工具: [/b][url=http://tools.jb51.net/code/char_tongji]http://tools.jb51.net/code/char_tongji[/url] 更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/168.htm]php常用函数与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部