【问题标题】:Find out the length of the longest word from list从列表中找出最长单词的长度
【发布时间】:2013-03-25 23:24:32
【问题描述】:

列表如下:

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";
}

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

【问题讨论】:

  • 拆分为数组;将 array_map() 与 strlen() 一起使用,然后找到 max() 值
  • 如何从字符串中一次取一行,保留最后一行的位置,然后从那里搜索到下一个新行
  • @Alex 你只想找到字符串中最长单词的长度?或者你想证明文本是合理的,所以它占据了一定的宽度?
  • 证明它的合理性。但是,如果我知道如何为每列获取最长的单词,我可以自己完成剩下的工作
  • 您是在设置宽度还是根据最长单词的长度确定宽度?

标签: php string performance


【解决方案1】:

如果文件非常大,您可以逐行读取文件,而不是将其全部加载到 使用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);

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

【讨论】:

  • 再次阅读您的问题,我意识到这不是您想要的。如果不运行两次文件,我看不到任何方法。第一次找到计算,第二次用所有空格创建一个新行。如果文件太大,第一次逐行读取文件,第二次运行时,逐行读取,但将结果逐行保存到新文件,直到完成。
猜你喜欢
  • 2013-01-16
  • 2021-12-29
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
相关资源
最近更新 更多