代码之家  ›  专栏  ›  技术社区  ›  Alex

找出列表中最长单词的长度

  •  0
  • Alex  · 技术社区  · 13 年前

    列表如下所示:

    Lorem ipsum dolor sit amet,
    consectetur adipisicing elit,
    sed do eiusmod tempor
    ...
    

    我想将所有单词缩进如下:

    Lorem       ipsum       dolor   sit    amet,
    consectetur adipisicing elit,
    sed         do          eiusmod tempor
    

    (或至少第一列)

    我已经使用阵列和 str_pad :

    $lines = explode("\n", $text);
    $counts = array();
    
    foreach($lines as $line){
      $words = explode(' ', $line);
      foreach($words as $index => $word){
        if(!isset($counts[$index]) || $counts[$index] < strlen($word))
          $counts[$index] = strlen($word);
      }
    }
    
    $text = '';
    
    foreach($lines as $line){
      $words = explode(' ', $line);
      foreach($words as $index => $word)
        $text .= str_pad($word, $counts[$index], ' ' , STR_PAD_RIGHT) . ' ';
    
      $text .= "\n";
    }
    

    但由于文本非常大,它占用了相当多的内存。有没有其他方法可以做到这一点,而不用将文本拆分成数组?

    1 回复  |  直到 13 年前
        1
  •  1
  •   jmm    13 年前

    如果文件非常大,您可以逐行读取文件,而不是将其全部加载到 一次数组 file() .

    $fh = fopen("alice.txt", "r");
    $fh = fopen("yourfile.txt", "r");
    
    while( !feof($fh) ){
    
        $line = fgets($fh);
        $Newerline = str_replace("-", " ", $line);
    
        $textArray = str_word_count($Newerline,1); 
    
        //now go through the line word by word
        foreach ($textArray as $index => $word){
            trim($word);
            $wordLength = mb_strlen($word);
    
            //is this word the longest for this column?
            if($wordLength > $longWords[$index]['longestWordlen'] ){
                $longWords[$index]['longestWordlen'] = $wordLength;
                $longWords[$index]['longestWord'] = $word;
            }
    
        }
        //echo $line;
    }
    //rewind the file pointer to the beginning
    rewind($fh);
    
    ksort($longWords);//associative array will be out of order since longest word shows up differently
    
    //now create a new file to hold the new version
    $fileh = fopen( "newFile.txt", "c");
    
    while( !feof($fh) ){
        $line = fgets($fh);
        $Newerline = str_replace("-", " ", $line); 
    
        $textArray = str_word_count($Newerline,1); 
    
        $newLine =  "";
        //now go through the line word by word
        foreach ($textArray as $index => $word){
            //set the length of this words column
                $pad_length = $longWords[$index]['longestWordlen'];
    
                $newLine .= str_pad($word, $pad_length + 1, " ", STR_PAD_RIGHT);
    
        }
        $newLine .= PHP_EOL;
    
        //save the newLine to file
        fwrite($fileh, $newLine);
    
        //echo $newLine;
    }
    
    fclose($fileh);
    fclose($fh);
    

    这样一次加载一行,一次写入一行。应该使用更少的内存。