zoukankan      html  css  js  c++  java
  • PHP:计算文件或数组中单词出现频率

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

        <?php  
        $str = file_get_contents("/path/to/file.txt"); //get string from file  
        preg_match_all("/(w+[-]w+)|(w+)/",$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);  
    

    Linux命令经典面试题:统计文件中出现次数最多的前10个单词

    使用linux命令或者shell实现:文件words存放英文单词,格式为每行一个英文单词(单词可以重复),统计这个文件中出现次数最多的前10个单词。

    cat words.txt | sort | uniq -c | sort -k1,1nr | head -10

      主要考察对sort、uniq命令的使用,相关解释如下,命令及参数的详细说明请自行通过man查看,简单介绍下以上指令各部分的功能:

    sort:  对单词进行排序

    uniq -c:  显示唯一的行,并在每行行首加上本行在文件中出现的次数

    sort -k1,1nr:  按照第一个字段,数值排序,且为逆序

    head -10:  取前10行数据

     

     

  • 相关阅读:
    转载-WebSocket协议解析
    django sqlite3数据迁入postgresql
    使用JenKins实现自动执行python脚本
    调用函数的局部变量
    打开新窗口获取元素
    邮箱登录脚本
    购物车小程序
    循环
    格式化的输出
    使用#号输出图形,可以指定宽和高
  • 原文地址:https://www.cnblogs.com/Alight/p/4443304.html
Copyright © 2011-2022 走看看